js实现页面的局部打印

1、其原理就是通过给打印dom设置id值,通过新建iframe,将需要打印的dom结构塞进iframe中,这样不会跳转页面,也不会刷新页面,防止本页面内容还没有处理完逻辑,而发生不必要的跳转,导致逻辑被刷新。

2、这要就会造成一个问题,引入外部样式出现问题,只能插入标签样式。

代码如下:

function prints(){
			  const el = document.getElementById('box');
			  const iframe = document.createElement('iframe');
			  let doc = null;
			  iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:500px;top:500px;background:blue');
			  document.body.appendChild(iframe);
			  doc = iframe.contentWindow.document;
			  // 引入打印的专有CSS样式
			  doc.write("<html><head>");
                //引入外部样式没有起作用
			  doc.write(`<link rel='stylesheet' type='text/css' href='./css/print.css'>`);
			  doc.write("</head><body>");
			  doc.write('<div style="width:100%;height:auto;min-width:1100px;margin:0px auto;"align="center">'+el.innerHTML+'</div>');
			  doc.write(el.innerHTML);
			  doc.write("</body></html>");       
			  var ys="html,body{height:100%}h2{color:red}";
			  var style=document.createElement("style");
                //该样式生效
			  style.innerText=ys;
			  doc.getElementsByTagName("head")[0].appendChild(style);
			  doc.close();
			  // 获取iframe的焦点,从iframe开始打印
			  iframe.contentWindow.focus();
			  iframe.contentWindow.print();
			  iframe.contentWindow.close();
			  if (navigator.userAgent.indexOf("MSIE") > 0)
			  {
			      document.body.removeChild(iframe);
			  }
			}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值