js print打印网页指定区域内容并携带样式

<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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。