2017-03-03 95 views
3

我有一個頁面,我打開一個新的窗口,像這樣添加媒體查詢從JS

var myWindow = window.open("", "", "width=755.9100,height=347.7200"); 
myWindow.document.body.append(img); 

我想一些風格從以前的窗口樣式添加到這個新窗口

@page {size: A4;margin: 0;@media print {html, body {width: 210mm;height: 297mm;} 

如何我是否通過js將它添加到HTML標頭中?

回答

3

還有就是window.matchMedia功能JS:

的用法很簡單:

if (window.matchMedia("(min-width: 400px)").matches) { 
    /* the viewport is at least 400 pixels wide */ 
} else { 
    /* the viewport is less than 400 pixels wide */ 
} 

一個更有用的物品是here

+1

有人能向我解釋爲什麼這是不是所選的答案嗎?我認爲這更清潔,更高效。 –

0

style也是一個HTML元素,這樣你就可以追加以類似的方式要附加img元素

var myWindow = window.open("", "", "width=755.9100,height=347.7200"); 
myWindow.document.body.append(img); 
var style = myWindow.document.createElement("style") 
style.innerHTML = "@page {size: A4;margin: 0;@media print {html, body {width: 210mm;height: 297mm;}" 
myWindow.document.head.append(style);