效果图如下:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="css/page/index.css">
<title>window调用打印接口</title>
<style>
#pr{width:100px;height:40px;line-height:40px;text-align:center;background:#ccc;}
.box{width:600px;background:red;}
</style>
</head>
<body>
<div class="box">
<h1>打印的内容</h1>
<p>局部内局部内容局部内容局部内容局部内容局部内容局部内容局</p>
</div>
<div id="tt">外部不打印的内容</div>
<div id="pr">点击打印</div>
</body>
</html>
<script>
function $(selector){
return document.querySelector(selector);
}
//打印页面全部
$("#pr").onclick =function(){
window.print();
}
/* 打印局部内容,原理:window.print会打印整个html显示的内容
* 那么想一下,如果要打印局部的内容怎么办好呢?换个思路,将要打印的页面的html先缓存起来,然后将要
* 打印的内容部分的html替换掉整个页面,调用方法打印,那么打印出来的就是局部的了,最后再将之前缓存
* 的html替换回去就好了。
* */
$("#pr").onclick =function(){
var oldHtml = $("body").innerHTML;
var printbox = $(".box").innerHTML;
$("body").innerHTML = printbox;
window.print();
$("body").innerHTML = oldHtml;
}
</script>