我想使用jQuery打印div的内容。这个问题已经在SO中被问到了,但是我找不到正确的(有效的)答案。
这是我的HTML:
<div id='printarea'>
<p>This is a sample text for printing purpose.</p>
<input type='button' id='btn' value='Print'>
</div>
<p>Do not print.</p>
在这里,我想打印div printarea
的内容。
我试过这个:
$("#btn").click(function () {
$("#printarea").print();
});
但当单击按钮时,它会给出一个控制台错误:
未捕获TypeError:$(...).print不是函数
但是当我尝试使用以下命令打印整个页面时
window.print();
它起作用了。但我只想打印特定div的内容。我在许多地方看到了答案$("#printarea").print();
,但这不起作用。
发布于 2015-11-16 20:28:16
一些jQuery研究失败了,所以我转到了JavaScript (感谢你的建议Anders)。
它工作得很好。
HTML
<div id='DivIdToPrint'>
<p>This is a sample text for printing purpose.</p>
</div>
<p>Do not print.</p>
<input type='button' id='btn' value='Print' onclick='printDiv();'>
JavaScript
function printDiv()
{
var divToPrint=document.getElementById('DivIdToPrint');
var newWin=window.open('','Print-Window');
newWin.document.open();
newWin.document.write('<html><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');
newWin.document.close();
setTimeout(function(){newWin.close();},10);
}
发布于 2015-11-16 18:11:41
发布于 2015-11-16 18:30:30
如果你想在没有额外插件(如printThis)的情况下做到这一点,我认为这应该是可行的。这个想法是要有一个特殊的div,它将被打印出来,而其他所有东西都使用CSS来隐藏。如果div是body标记的直接子标记,则更容易做到这一点,因此您必须将想要打印的任何内容移动到这样的div中。首先创建一个id为print-me
的div,作为body标记的直接子标记。然后使用以下代码打印div:
$("#btn").click(function () {
//Copy the element you want to print to the print-me div.
$("#printarea").clone().appendTo("#print-me");
//Apply some styles to hide everything else while printing.
$("body").addClass("printing");
//Print the window.
window.print();
//Restore the styles.
$("body").removeClass("printing");
//Clear up the div.
$("#print-me").empty();
});
您需要的样式如下:
@media print {
/* Hide everything in the body when printing... */
body.printing * { display: none; }
/* ...except our special div. */
body.printing #print-me { display: block; }
}
@media screen {
/* Hide the special layer from the screen. */
#print-me { display: none; }
}
当存在printing
类时,我们应该只应用@print
样式的原因是,如果用户通过选择File -> Print
来打印页面,则应该像往常一样打印页面。
https://stackoverflow.com/questions/33732739
复制相似问题