Is there a way to enable media print css to a normal view?

自作多情 提交于 2019-12-13 07:25:41

问题


I developed a website with a bunch of print media queries to align stuff when printing the page. when you go to the print mode on web browser, the queries works great. but i want apply/remove those @media print queries on a regular web page without having to go into the printing mode.(by clicking a button) is there any way to achieve this?


回答1:


In addition to Boldewyn's answer, if you have @media print styles inside <style> tags, you can replace them with @media screen:

Array.prototype.forEach.call(document.getElementsByTagName('style'), function(style) {
    style.innerText = style.innerText.replace(/@media print/gi, '@media screen');
});

See the demo.




回答2:


To add to yezzz's answer: If you have the print CSS linked in the HTML like

<link rel="stylesheet" media="print" href="...">

you can remove the media attribute to enable those styles everywhere, either on the server or with Javascript:

document.querySelector('[media="print"]').removeAttribute('media');

Note, that this doesn't work, if the statements in the print stylesheet are wrapped in a @media print {} rule.




回答3:


First thing that comes to mind is use classes. Simple example to give you the general idea. If you had a button that toggles emulateprint class on the body you could use eg. this css:

body {
  color: black;
}
body.emulateprint {
  /* put same styles as @media print in here */
  color: red;
}

@media print {
  body {
    color:red;
  }
}


来源:https://stackoverflow.com/questions/37080744/is-there-a-way-to-enable-media-print-css-to-a-normal-view

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