当前页面
var bodyHtml = window.document.body.innerHTML; window.document.body.innerHTML = printHtml;//printHtml为当前需要打印的div的内容 window.print(); window.document.body.innerHTML = bodyHtml; 缺点: (1)移除页面内容再插入需要打印页面内容,页面会有一个大的跳动 (2)页面事件效果会丢失
iframe 打印
function myPrint(){ var el = "<div>Content should be print!</div>"; var iframe = document.createElement('IFRAME'); iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;'); document.body.appendChild(iframe); var doc = iframe.contentWindow.document; doc.write(el); var pageStyle="html,body{height:100%}img{max-width:100%;max-height:100%;margin:0 auto}"; var style=document.createElement("style"); style.innerText= pageStyle; doc.getElementsByTagName("head")[0].appendChild(style) doc.close(); iframe.contentWindow.focus(); iframe.contentWindow.print();
)
缺点: 需要将所有style拷贝到iframe
media query 实现
@media print { .no-need-print-block { display: none; } }
缺点: 一块多个地方复用的模块不好customize