比较简单的办法
使用CSS,定义一个.noprint的class,将不打印的内容放入这个class内。
细如下:
代码如下
.noprint{visibility:hidden}
要打印的内容。哈哈!
代码如下
方法二利用js来操作
代码如下
function preview()
{
bdhtml=window.document.body.innerHTML;
sprnstr="";
eprnstr="";
prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17);
prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));
window.document.body.innerHTML=prnhtml;
window.print();
}
或者这样也可以
代码如下
function printpage(myDiv){
//var newstr = document.all.item(myDiv).innerHTML;
var newstr = document.getElementById(myDiv).innerHTML;
var oldstr = document.body.innerHTML;
document.body.innerHTML = newstr;
window.print();
document.body.innerHTML = oldstr;
return false;
}
上面js没测试过兼容性我们可使用jquery来设置
代码如下
jquery 打印指定区域内容function printHtml(html) {
var bodyHtml = document.body.innerHTML;
document.body.innerHTML = html;
window.print();
document.body.innerHTML = bodyHtml;
}
function onprint() {
var html = $("#printArea").html();
printHtml(html);
}
打印区域~~~~
下面看看我自己实例的一种办法,原理是这样
JavaScript打印页面指定div区域原理:使用window.open()在浏览器打开一个新的页面(window), 使用 window.document.write()将指定div区域的内容写入新窗口文档,document.close()关闭文档,使用window.print()调用打印机打印当前文档
JavaScript打印函数myPrint(obj):
代码如下
function myPrint(obj){
//打开一个新窗口newWindow
var newWindow=window.open("打印窗口","_blank");
//要打印的div的内容
var docStr = obj.innerHTML;
//打印内容写入newWindow文档
newWindow.document.write(docStr);
//关闭文档
newWindow.document.close();
//调用打印机
newWindow.print();
//关闭newWindow页面
newWindow.close();
}
myprint()调用方法:
myPrint(document.getElementById('printDivID'));
例
代码如下
function myPrint(obj){
var newWindow=window.open("打印窗口","_blank");
var docStr = obj.innerHTML;
newWindow.document.write(docStr);
newWindow.document.close();
newWindow.print();
newWindow.close();
}
打印演示区域,点击打印后会在新窗口加载这里的内容!
打 印