单击按钮时如何打印 HTML 内容,而不是页面? [英] How to print HTML content on click of a button, but not the page?

查看:44
本文介绍了单击按钮时如何打印 HTML 内容,而不是页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用户单击按钮时打印一些 HTML 内容.一旦用户点击该按钮,浏览器的打印对话框将打开,但不会打印网页.相反,它会打印一些未在页面上显示的其他 HTML 内容.

在问这个问题时,我想到的解决方案很少.但我不确定这些是好主意还是可以做一些更好的事情.其中一种解决方案是:我可以将此 HTML 内容保存在一个 div 中,并使其 display: 打印,但 display: none 显示.网页上的所有其他元素都可以设为 display: none 用于打印,display: 用于屏幕.然后调用打印.

有什么更好的主意吗?

解决方案

@media print {.noPrint{显示:无;}}h1{颜色:#f6f6;}

打印我

<h1 class="noPrint">没有印刷品<button onclick="window.print();"class="noPrint">打印我</button>

我遇到了另一个优雅的解决方案:

将您的可打印部分放在一个 div 中,其 id 如下所示:

<h1>打印我</h1>

<输入类型=按钮"onclick="printDiv('printableArea')";value="打印一个 div!";/>

现在让我们创建一个非常简单的javascript:

function printDiv(divName) {var printContents = document.getElementById(divName).innerHTML;var originalContents = document.body.innerHTML;document.body.innerHTML = 打印内容;窗口.打印();document.body.innerHTML = originalContents;}

来源:SO 答案

I want to print some HTML content, when the user clicks on a button. Once the user clicks on that button, the print dialog of the browser will open, but it will not print the webpage. Instead, it will print the some other HTML content which is not displayed on the page.

While asking this question, there are few solutions coming into my mind. But I am not sure whether those are good ideas or something better can be done. One of those solutions are: I can keep this HTML content in a div and make it display: to print, but display: none to screen. All other elements on the webpage can be made to display: none for print and display: for the screen. And then call to print.

Any better idea?

解决方案

@media print {
  .noPrint{
    display:none;
  }
}
h1{
  color:#f6f6;
}

<h1>
print me
</h1>
<h1 class="noPrint">
no print
</h1>
<button onclick="window.print();" class="noPrint">
Print Me
</button>

I came across another elegant solution for this:

Place your printable part inside a div with an id like this:

<div id="printableArea">
      <h1>Print me</h1>
</div>

<input type="button" onclick="printDiv('printableArea')" value="print a div!" />

Now let's create a really simple javascript:

function printDiv(divName) {
     var printContents = document.getElementById(divName).innerHTML;
     var originalContents = document.body.innerHTML;

     document.body.innerHTML = printContents;

     window.print();

     document.body.innerHTML = originalContents;
}

SOURCE : SO Answer

这篇关于单击按钮时如何打印 HTML 内容,而不是页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆