做项目时,有在网页实现全局和局部打印的需求,百度许久,现总结如下:
打印方式一:
1.首先在head里面加入下面一段js代码:
function preview(fang)
{
if (fang < 10){
bdhtml=window.document.body.innerHTML;//获取当前页的html代码
sprnstr="<!--startprint"+fang+"-->";//设置打印开始区域
eprnstr="<!--endprint"+fang+"-->";//设置打印结束区域
prnhtml=bdhtml.substring(bdhtml.indexOf(sprnstr)+18); //从开始代码向后取html
prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));//从结束代码向前取html
window.document.body.innerHTML=prnhtml;
window.print();
window.document.body.innerHTML=bdhtml;
} else {
window.print();
}
}
2.然后在所需要打印的代码,用和包围着,如下:
<!--startprint1-->
<!--打印内容开始-->
<!-- <div id=wdf>
...
</div>
打印内容结束-->
<!--endprint1-->
3.最后加上一个打印的按钮
<input type='button' name='button_export' title='打印1' οnclick=preview(1) value='打印1'>
打印方式二:
1.javascript中方法为:
function dayin(){
var userAgent = navigator.userAgent.toLowerCase(); //取得浏览器的userAgent字符串
if (userAgent.indexOf("trident") > -1){
alert("请使用google或者360浏览器打印");
return false;
}else if(userAgent.indexOf('msie')>-1){
var onlyChoseAlert = simpleAlert({
"content":"请使用Google或者360浏览器打印",
"buttons":{
"确定":function () {
onlyChoseAlert.close();
}
}
})
alert("请使用google或者360浏览器打印");
return false;
}else{//其它浏览器使用lodop
var oldstr = document.body.innerHTML;
var headstr = "<html><head><title></title></head><body>";
var footstr = "</body>";
//执行隐藏打印区域不需要打印的内容
document.getElementById("otherpho").style.display="none";
//此处id换为你自己的id
var printData = document.getElementById("printdivaa").innerHTML; //获得 div 里的所有 html 数据
document.body.innerHTML = headstr+printData+footstr;
window.print();
//打印结束后,放开隐藏内容
document.getElementById("otherpho").style.display="block";
document.body.innerHTML = oldstr ;
}
}
2.页面内容如下:
<div id='printdivaa'>
...
</div>
<div id="otherpho"></div>
3.页面中放置一个打印按钮:
<button type="button" class="btn_search" onclick="dayin()">打印</button>
打印方式三(此方式会重新打开一个浏览器窗口):
1.javascript中方法为:
function dayin() {
var userAgent = navigator.userAgent.toLowerCase(); //取得浏览器的userAgent字符串
if (userAgent.indexOf("trident") > -1) {
alert("请使用google或者360浏览器打印");
return false;
} else if (userAgent.indexOf('msie') > -1) {
var onlyChoseAlert = simpleAlert({
"content" : "请使用Google或者360浏览器打印",
"buttons" : {
"确定" : function() {
onlyChoseAlert.close();
}
}
})
alert("请使用google或者360浏览器打印");
return false;
} else {//其它浏览器使用lodop
var oldstr = document.body.innerHTML;
var headstr = "<html><head><title></title></head><body>";
var footstr = "</body></html>";
//执行隐藏打印区域不需要打印的内容
document.getElementById("otherpho").style.display="none";
var printData = document.getElementById("studentPhoTable").innerHTML; //获得 div 里的所有 html 数据
var wind = window.open("", "newwin",
"toolbar=no,scrollbars=yes,menubar=no");
wind.document.body.innerHTML = headstr + printData + footstr;
wind.print();
//打印结束后,放开隐藏内容
document.getElementById("otherpho").style.display="block";
wind.close();
window.document.body.innerHTML = oldstr;
}
}
2.页面内容如下:
<div id='studentPhoTable'>
...
</div>
3.页面中放置一个打印按钮:
<input type="button" οnclick="print()" value="确定打印" />