【问题标题】:Print a specific div from a page via pressing ctrl+p通过按 ctrl+p 从页面打印特定的 div
【发布时间】:2016-03-10 07:36:44
【问题描述】:

当我通过键盘按下默认打印按钮时,我想从网页打印div。但我不知道该怎么做。

我尝试使用keypress,但如果我按任意键,它就会打印出来 键盘,但如果按下键对ctrl+p,我想打印。

我尝试类似:

$(document).bind('keypress', 'ctrl+p', printContent);
function printContent(){
    var restorepage = document.body.innerHTML;
    var printcontent = document.getElementById("print_div").innerHTML;
    document.body.innerHTML = printcontent;
    window.print();
    document.body.innerHTML = restorepage;
}

HTML

<h1>My Print page</h1>
<div id="print_div">
    It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
</div>

如果有人给我这个想法,那么它将对我有所帮助。

提前致谢。

【问题讨论】:

  • 为什么不对打印媒体使用 CSS 规则,以确保除所需 div 之外的所有内容都是 display: none
  • 我对此一无所知。如果有任何参考,请提供。
  • @FrayneKonok developer.mozilla.org/en-US/docs/Web/CSS/@media 使用@media print 然后将所有不需要的元素设为display: none
  • @RoryMcCrossan,是否支持跨浏览器或我需要手动执行?
  • 兼容性图表在该页面的底部。 @media print 完全支持一切,回到 IE6。

标签: javascript jquery printing


【解决方案1】:

使用此代码:

<html>
<head>
<script src="http://www.openjs.com/scripts/events/keyboard_shortcuts/shortcut.js"></script>
    <script language="javascript" type="text/javascript">

        shortcut.add("ctrl+p", function() {

        var myDiv = document.getElementById("ID").innerHTML;
            var oldPage = document.body.innerHTML;
            document.body.innerHTML = 
              "<html><head><title></title></head><body>" + 
              myDiv + "</body>";
            window.print();
            document.body.innerHTML = oldPage;
            });

    </script>

</head>
<body>
    <div id="ID">
        print only this div
    </div>
    <div>
        this will NOT be printed
    </div>

</body>
</html>

【讨论】:

    【解决方案2】:

    正如 cmets 中所说,您应该查看@media print css 标记。 当任何用户执行 ctrl / cmd + P 时,您可以隐藏您不想打印的任何元素,这样可以节省一些墨水和时间。

    【讨论】:

      猜你喜欢
      • 2018-12-24
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-31
      • 1970-01-01
      相关资源
      最近更新 更多