window.print()默认打印整个页面,可是我只想打印页面的部分样式,最简单的一种方法是使用 css 的媒体查询有针对打印的样式,用@media print设置打印时除了要打印的内容,其它全部隐藏即可
<!doctype html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title><style>/*设置打印样式*//*浏览器默认情况下并不能打印出CSS中的背景内容*//*打印设置使用的是物理单位,所以尺寸最好不要用像素(px),可以用pt也可以用cm*//*尽量不要让内容浮动,有些浏览器打印浮动的div的过程中,会有一个麻烦*/@media print {BODY {font-size:36pt;color: deeppink;background: pink;} }</style><!-- 打印时display:none隐藏样式--><style media="print">.noPrint {display: none;}</style><!-- 页面上的样式--><style media="screen">.print {width: 300px;height: 300px;background: pink;}.noPrint {width: 300px;height: 300px;background: #2eabff;}</style></head><body><h1 class="print">打印的页面</h1><h2 class="noPrint">不打印的页面</h2><button onclick="window.print()">打印我</button></body></html>