js调用iframe实现打印页面内容的方法

前端技术 2023/09/05 JavaScript

1、程序说明

1) 此程序可以实现选择页面中的区域进行打印,以iframe方式进行打印;
2) 与原生态的print() 区别在于,取消打印页面后可以完整保留当前访问页面的内容。

2、代码部分

1) JS 函数:

复制代码 代码如下:

function do_print(id_str)//id-str 打印区域的id
{
var el = document.getElementById(id_str);
var iframe = document.createElement(\'IFRAME\');
var doc = null;
iframe.setAttribute(\'style\', \'position:absolute;width:0px;height:0px;left:-500px;top:-500px;\');
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
// 引入打印的专有CSS样式,www.111Cn.net根据实际修改
doc.write(\"<LINK rel=\"stylesheet\" type=\"text/css\" href=\"css/print.css\">\");
doc.write(\'<div>\' + el.innerHTML + \'</div>\');
doc.close();
iframe.contentWindow.focus();
iframe.contentWindow.print();
if (navigator.userAgent.indexOf(\"MSIE\") > 0)
{
     document.body.removeChild(iframe);
}
}

2) HTML:

复制代码 代码如下:

// 打印区域:
<div id=\"print_box\">
......
</div>
// 调用打印
<button onclick=\"javascript:do_print(\'print_box\');\">打印</button>


3. 测试

点击页面上的打印按钮,即可测试打印;

除了上面方法我们还可以通过jquery来实例,代码如下

复制代码 代码如下:

<script type=\"text/javascript\" src=\"jquery-1.4.2.min.js\"></script>
<script type=\"text/javascript\" src=\"jquery.PrintArea.js\"></script>
<script>
$(document).ready(function(){
  $(\"input#biuuu_button\").click(function(){

  $(\"div#myPrintArea\").printArea();

});
});
</script>
<input id=\"biuuu_button\" type=\"button\" value=\"打印\"></input>
<div id=\"myPrintArea\">.....文本打印部分.....</div>

本文地址:https://www.stayed.cn/item/13548

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。