Home > Article > Web Front-end > js implementation of partial page print preview principle and sample code_javascript skills
Recently, a friend asked how to print preview in js. Today I will explain it. First, let’s understand the printing principle. In fact, partial printing of the page is very simple. Just make a starting mark for the part you want to print. As for how to write the mark, you can write whatever you want. I will write here deb9743a1dda5b69a1ef24bbfc365042 the content that needs to be printed
c474806c1b49f890ebb5bd06e2d26ef3. Because the markup does not need to be seen by users, I added a comment! The specific implementation code is as follows:
<!DOCTYPE html> <html> <head> <title>打印预览简单实现</title> </head> <body> <div> 这是body 里的内容不需要打印,具体的页面设计根据自己的要求自行设计。如果需要一个页面多个tag,可以动态生成tag </div> <!--startprint--> <div> 这是我需要打印的内容 </div> <!--endprint--> <script type="text/javascript"> function preview() { var bdhtml=window.document.body.innerHTML;//获取当前页的html代码 var startStr="<!--startprint-->";//设置打印开始区域 var endStr="<!--endprint-->";//设置打印结束区域 var printHtml=bdhtml.substring(bdhtml.indexOf(startStr)+startStr.length,bdhtml.indexOf(endStr));//从标记里获取需要打印的页面 window.document.body.innerHTML=printHtml;//需要打印的页面 window.print(); window.document.body.innerHTML=bdhtml;//还原界面 } preview(); </script> </body> </html>