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

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

问题描述

我想打印一些HTML内容,当用户点击一个按钮。一旦用户点击该按钮,浏览器的打印对话框将打开,但不会打印网页。



在提出这个问题时,几乎没有解决方案进入我的脑海。但我不知道这些是好的想法还是更好的可以做。其中一个解决方案是:
我可以保持这个HTML内容在一个div,并使它显示:打印,但显示:无到屏幕。网页上的所有其他元素可以作为屏幕的 display:none 以打印和显示:

解决方案

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



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

 < div id =printableArea> 
< h1>打印我< / h1>
< / div>

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

现在让我们创建一个非常简单的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:回答


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?

解决方案

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天全站免登陆