Use window.print() to print the specified content and print it on one page

Use window.print() to print the specified content and print it onone pagepaper

html

<!-- 打印的内容会生成两页纸 -->
 <div id="report">
 	<h1>..</h1>  <----重点
    <div>..</div>
</div>  

javscript

 function doPrint(){
    //根据div标签ID拿到div中的局部内容
    let bdhtml=window.document.body.innerHTML;
    let jubuData = document.getElementById("report").innerHTML;
    //把获取的 局部div内容赋给body标签, 相当于重置了 body里的内容
    window.document.body.innerHTML= jubuData;
    //调用打印功能
    window.print();
    window.document.body.innerHTML=bdhtml;//重新给页面内容赋值;
    return false;
  }

Precautions

If the first child element within the element that needs to be printed is H1~H5, two pages will appear.two pages

Guess you like

Origin blog.csdn.net/web_houzhanguo/article/details/121267704