浏览器打印部分区域内容

1.打开一个新窗口并把要打印的区域赋值给新窗口

var newWindow = window.open('打印窗口', '_blank')
var docStr = document.getElementById('print').innerHTML
newWindow.document.write(docStr)
newWindow.document.close()
newWindow.print()
newWindow.close()

缺点:新的页面没有样式

2.把doument.body内容替换成要打印区域的内容,打印完后再替换回去

var headstr = '<html><head><title></title></head><body>'
var footstr = '</body>'
var newstr = document.getElementById('print').innerHTML
var oldstr = document.body.innerHTML
document.body.innerHTML = headstr + newstr + footstr
window.print()
document.body.innerHTML = oldstr
return false

确定:把原来内容重新赋值给document.body后,页面链接不可点击,变成静态页面,必须重新刷新页面才可用

3.借助于iframe框架

var el = document.getElementById('print')
var iframe = document.createElement('IFRAME')
var doc = null
iframe.setAttribute('style', 'position:absolute;0px;height:0px;left:-500px;top:-500px;')
document.getElementsByTagName('th')[0].setAttribute('style', 'text-align:left')
document.getElementsByTagName('th')[1].setAttribute('style', 'text-align:left')
document.getElementsByClassName('expand-trigger')[0].setAttribute('style', 'height:0px')
document.body.appendChild(iframe)
doc = iframe.contentWindow.document
doc.write('<div>' + el.innerHTML + '</div>')
doc.close()
iframe.contentWindow.focus()
iframe.contentWindow.print()
if (navigator.userAgent.indexOf('MSIE') > 0) {
document.body.removeChild(iframe)
}

 目前没有找到新的方法,后续会补新的方法

原文地址:https://www.cnblogs.com/yang1215/p/7793942.html