js实现IE、谷歌浏览器打印网页内容

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_30856231/article/details/79760345

分享一种通用的打印网页、文本内容的方法.经测试,此方法兼容IE8~IE11及chrome浏览器。

window.print()

此方法会弹出打印对话框,打印的是window.document.body.innerHTML中的内容 。

html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>打印文本内容</title>
  <link rel="stylesheet" type="text/css" href="***.css">
</head>
<script type="text/javascript" src="/externals/jquery-1.10.2/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="/js/affair-detail.js"></script>
<style media="print">
  @page{
    size:auto;  /* auto is the initial value */
    margin:0mm; /* this affects the margin in the printer settings */
  }
</style>
<body>
<div class="content">
  <div class="back">返回</div>
  <!--startprint-->
  <div class="printBox">
    <div class="header">
      ———
      <span>打印内容</span>
      ———
    </div>
  </div>
  <!--endprint-->
  <div class="others">其他内容</div>
  <button class="btn" onclick="preview();">打印</button>
</div>
</body>
</html>

javascript:
js处理,判断浏览器类型(IE/谷歌)。截取需要打印的部分进行打印,去掉页眉页脚

/**
 * 打印文本内容
 * */
function preview(){
  $('.printBox').css({padding: '30px'}); //针对打印部分进行样式调整,打印完后恢复原内容
  bdhtml = window.document.body.innerHTML;
  sprnstr = "<!--startprint-->";
  eprnstr = "<!--endprint-->";
  prnhtml = bdhtml.substr(bdhtml.indexOf(sprnstr) + 17);
  prnhtml = prnhtml.substring(0, prnhtml.indexOf(eprnstr));
  window.document.body.innerHTML = prnhtml;
  if(!!window.ActiveXObject || "ActiveXObject" in window) { //是否ie
    remove_ie_header_and_footer();
  }
  window.print();
  window.document.body.innerHTML = bdhtml;
  $('.printBox').css({padding: '0'});
}
/**
 * 移除页眉页脚
 * */
function remove_ie_header_and_footer(){
  var hkey_path;
  hkey_path = "HKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer\\PageSetup\\";
  try {
    var RegWsh = new ActiveXObject("WScript.Shell");
    RegWsh.RegWrite(hkey_path + "header", "");
    RegWsh.RegWrite(hkey_path + "footer", "");
  } catch(e) {
  }
}

猜你喜欢

转载自blog.csdn.net/qq_30856231/article/details/79760345
今日推荐