【JS】调用浏览器打印功能
参考文献:https://blog.csdn.net/qq_32540639/article/details/74909891
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>局部打印案例</title>
<script type="text/javascript">
function doPrint() {
//取得浏览器的userAgent字符串
bvar userAgent = navigator.userAgent.toLowerCase();
if (userAgent.indexOf("trident") > -1 || userAgent.indexOf('msie') > -1) {
alert("请使用google或者360浏览器打印");
return false;
}
// 打印
bdhtml = window.document.body.innerHTML;//获取当前页的html代码
sprnstr = "<!--startprint-->";//设置打印开始区域
eprnstr = "<!--endprint-->";//设置打印结束区域
prnhtml = bdhtml.substring(bdhtml.indexOf(sprnstr) + 17); //从开始代码向后取html
prnhtml = prnhtml.substring(0, prnhtml.indexOf(eprnstr));//从结束代码向前取html
window.document.body.innerHTML = prnhtml;
window.print();
window.document.body.innerHTML = bdhtml;
}
</script>
</head>
<body>
<p>1不需要打印的地方</p>
<p>2这里不要打印啊</p>
<!--startprint--><!--注意要加上html里star和end的这两个标记-->
<div class="m-page" contenteditable="true">
<h1>打印标题</h1>
<p>打印内容</p>
</div>
<!--endprint-->
<button type="button" onclick="doPrint()">打印</button>
<p>不打印的地方啊哈哈哈哈</p>
<p>2</p>
</body>
</html>
【注意】contenteditable属性,将页面需要打印部分的功能可以点击编辑,再打印
得意时做事,失意时读书

浙公网安备 33010602011771号