<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js print打印网页指定区域内容的简单实例</title>
<style>
.print-content {
color: red;
}
</style>
</head>
<script>
function myPrint(obj){
var newWindow=window.open("打印窗口","_blank");
var docStr = obj.innerHTML;
newWindow.document.write(docStr);
// 打印窗口需要携带样式
var styles = Array.from(window.document.styleSheets)[0];
var styleText = Array.from(styles.rules).filter(rule => [".print-content"].includes(rule.selectorText)).map(rule => rule.cssText).join(';')
newWindow.document.head.innerHTML = `<style>${styleText}</style>`
newWindow.document.close();
newWindow.print();
newWindow.close();
}
</script>
<div id="print">
<hr />
<div class='print-content'>
打印演示区域,点击打印后会在新窗口加载这里的内容!
</div>
<hr />
</div>
<button onclick="myPrint(document.getElementById('print'))">打 印</button>
</html>
网友评论