首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用Jquery打印div内容

使用Jquery打印div内容
EN

Stack Overflow用户
提问于 2015-11-16 18:07:35
回答 13查看 278.4K关注 0票数 44

我想使用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();,但这不起作用。

EN

回答 13

Stack Overflow用户

回答已采纳

发布于 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);

}
票数 80
EN

Stack Overflow用户

发布于 2015-11-16 18:11:41

https://github.com/jasonday/printThis

$("#myID").printThis();

很棒的Jquery插件,可以做你想做的事

票数 38
EN

Stack Overflow用户

发布于 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来打印页面,则应该像往常一样打印页面。

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33732739

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档