使用JavaScript添加媒体查询

4

我有一个页面,在该页面中我打开了一个新窗口,如下所示:

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;}

我该如何通过JavaScript将这段代码添加到HTML的头部标签中?
3个回答

5

在JavaScript中有一个名为window.matchMedia的函数:

使用非常简单:

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

这里有一篇更加有用的文章,请点击此处


1
这仅适用于加载时。正确的答案应该有一个渲染的媒体查询,可以动态响应窗口大小的变化。 - Manny Alvarado

3

style也是HTML元素,所以您可以像添加元素一样添加它。

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);

1
请注意,检查 MediaQueryList.matches 实际上不会向 CSS 添加媒体查询。 您必须在每次窗口更改时运行此检查。 为此,除了直接检查 matches 属性之外,还应在 MediaQueryList 上调用 addListener(callback)
例如,要将样式应用于打印页面上的 <html><body> 元素:
let mediaQueryList = window.matchMedia("print");
function screenTest(e) {
    if (e.matches) {
        document.documentElement.style.width = "210mm";
        document.body.style.width = "210mm";
        document.documentElement.style.width = "297mm";
        document.body.style.width = "297mm";
    }
    else {
        document.documentElement.style.width = null;
        document.body.style.width = null;
    }
}
screenTest(mediaQueryList);
mediaQueryList.addListener(screenTest);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接