如何打印指定的div(无需手动禁用页面上的所有其他内容)?
我想要避免一个新的预览对话框,所以用这个内容创建一个新窗口是没有用的。
该页面包含了几个表格,其中一个包含了我想打印的div -表格是用web的视觉样式设计的,不应该显示在打印中。
如何打印指定的div(无需手动禁用页面上的所有其他内容)?
我想要避免一个新的预览对话框,所以用这个内容创建一个新窗口是没有用的。
该页面包含了几个表格,其中一个包含了我想打印的div -表格是用web的视觉样式设计的,不应该显示在打印中。
当前回答
我有多个图像,每个图像都有一个按钮,需要单击一个按钮来打印每个带有图像的div。如果我在浏览器中禁用了缓存,并且图像大小在Chrome中没有改变,这个解决方案就可以工作:
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
w = window.open();
w.document.write(printContents);
w.document.write('<scr' + 'ipt type="text/javascript">' + 'window.onload = function() { window.print(); window.close(); };' + '</sc' + 'ript>');
w.document.close(); // necessary for IE >= 10
w.focus(); // necessary for IE >= 10
return true;
}
<div id="printableArea">
<h1>Print me</h1>
</div>
<input type="button" onclick="printDiv('printableArea')" value="print a div!" />
其他回答
使用特殊的样式表进行打印
<link rel="stylesheet" href="print.css" type="text/css" media="print" />
然后添加一个类,即。"noprint"到每个你不想打印的内容的标签。
在CSS中使用
.noprint {
display: none;
}
在css3中,你可以使用以下功能:
body *:not(#printarea) {
display: none;
}
嗯……使用样式表的类型进行打印…例如:
<link rel="stylesheet" type="text/css" href="print.css" media="print" />
print.css:
div { display: none; }
#yourdiv { display: block; }
我尝试了提供的许多解决方案。没有一个是完美的。它们要么丢失CSS绑定,要么丢失JavaScript绑定。我找到了一个完美而简单的解决方案,既不会丢失CSS也不会丢失JavaScript绑定。
HTML:
<div id='printarea'>
<p>This is a sample text for printing purpose.</p>
<input type='button' id='btn' value='Print' onclick='printFunc();'>
</div>
<p>Do not print.</p>
Javascript:
function printFunc() {
var divToPrint = document.getElementById('printarea');
var htmlToPrint = '' +
'<style type="text/css">' +
'table th, table td {' +
'border:1px solid #000;' +
'padding;0.5em;' +
'}' +
'</style>';
htmlToPrint += divToPrint.outerHTML;
newWin = window.open("");
newWin.document.write("<h3 align='center'>Print Page</h3>");
newWin.document.write(htmlToPrint);
newWin.print();
newWin.close();
}
桑德罗的方法很有效。
我对它进行了调整,以允许多个printMe链接,特别是在选项卡页面和扩展文本中使用。
function processPrint(printMe){<——在这里调用一个变量
var printReadyElem = document.getElementById(printMe);<——删除了printMe周围的引号以请求一个变量
< a href = " javascript:无效(processPrint (' divID '));>Print</a> <——将要打印的div ID传递到函数上,将printMe变量转换为div ID。需要单引号