Home > Web Front-end > JS Tutorial > body text

js implementation of partial page print preview principle and sample code_javascript skills

WBOY
Release: 2016-05-16 16:42:38
Original
2120 people have browsed it

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 the content that needs to be printed

. 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>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!