How to use Javascript to popup a new window with NEARLY the same html as its parent window

岁酱吖の 提交于 2019-12-10 18:08:19

问题


I want to create multiple versions of print-friendly pages from a single page. I am considering to do it in this way: placing several buttons on the original page and, clicking one button will popup a new window with the same html as its parent window, but with some modifications (e.g., set display attribute of some DIV's to none).

It is possible to use javascript to do this?


回答1:


You could pass an additional parameter to the current page's url and open it in a new window, like this:

window.open(document.location.href + "?print=true");

You can then read the URL parameter in JavaScript and do the necessary hiding and CSS alterations to make the document print friendly.

Speaking of which: Why not use a print-only CSS that does this for you? Then all you need to do in your code is:

window.print();

And in your document HEAD:

<link rel="stylesheet" href="yourcssfile.css" media="print" /> 

And the CSS will make sure the page looks the way you want to in print. See this article for more about printing in CSS.




回答2:


Yes, it's possible to setup javascript code to to this, something like:

window.open('myPage.html')

getElementById('<someid>').style.display = none

However, you may want to look into CSS print stylesheets, which allow to use CSS to specify the div hidings and whatnot. It has the advantage of not forcing the user to open a pop-up window and not taking the second page-load hit on your server. I found this article to be a good place to get started.

Basically, to add a print stylesheet you setup a link like this:

<link rel="stylesheet" type="text/css" media="print" href="myPrintStyles.css"/>


来源:https://stackoverflow.com/questions/2531286/how-to-use-javascript-to-popup-a-new-window-with-nearly-the-same-html-as-its-par

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!