打印页面指定区域
function printNode(el) {
//判断iframe是否存在,不存在则创建iframe
var iframe = document.getElementById("print-iframe");
if (!iframe) {
iframe = document.createElement('IFRAME');
var doc = null;
iframe.setAttribute("id", "print-iframe");
iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
var head = document.createDocumentFragment()
Array.from(document.head.children).forEach(node => {
head.appendChild(node.cloneNode(true))
})
doc.head.appendChild(head)
var printStyle = document.createElement('style')
printStyle.setAttribute('media', 'print');
printStyle.innerHTML = '@page {size: auto;margin: 0mm;}';
doc.head.appendChild(printStyle)
console.log([head], doc.head)
//这里可以自定义样式
doc.body.appendChild(el.cloneNode(true))
doc.close();
iframe.contentWindow.focus();
}
setTimeout(function () { iframe.contentWindow.print(); }, 1000) //解决第一次样式不生效的问题
if (navigator.userAgent.indexOf("MSIE") > 0) {
document.body.removeChild(iframe);
}
}
window.print()
// 打印时,可以把打印的 区域内容,加一个class ,全屏定位显示在窗口,zIndex大一点
window.onbeforeprint = () => console.log('打印前');
// // 打印后,或者取消打印。都可以移除class,来取消全屏定位;恢复打印前的样子
window.onafterprint= () => console.log('打印后');
网友评论