Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

javascript - 如何在单击按钮时打印HTML内容,而不是页面? [重复](How to print HTML content on click of a button, but not the page? [duplicate])

This question already has an answer here:

(这个问题在这里已有答案:)

I want to print some HTML content, when the user clicks on a button.

(当用户点击按钮时,我想打印一些HTML内容。)

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.

(相反,它将打印一些未显示在页面上的其他HTML内容。)

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.

(其中一个解决方案是:我可以将这个HTML内容保存在div中并使其display:打印,但display: none屏幕。)

All other elements on the webpage can be made to display: none for print and display: for the screen.

(可以使网页上的所有其他元素display: none用于打印和display:用于屏幕。)

And then call to print.

(然后打电话给打印。)

Any better idea?

(有什么好主意吗?)

  ask by Debiprasad translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I came across another elegant solution for this:

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

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

(将您的可打印部分放在一个id为div的div中:)

<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:

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

(消息来源: SO答案)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...