使用javascript或jQuery生成CSS媒体查询

Generating CSS media queries with javascript or jQuery

本文关键字:CSS 媒体 查询 生成 jQuery javascript 使用      更新时间:2023-09-26

是否可以使用Javascript或jQuery在飞行中创建完整的媒体查询规则?

我已经使用了大量的媒体查询来针对通用的视口和特定的设备/屏幕使用内联CSS,导入和链接文件:

@media screen and (min-width:400px) { ... }
@import url(foo.css) (min-width:400px);
<link rel="stylesheet" type="text/css" media="screen and (min-width: 400px)" href="foo.css" />

我可以使用jQuery添加/删除类:

$("foobar").click(function(){
  $("h1,h2,h3").addClass("blue");
  $("div").addClass("important");
  $('#snafu').removeClass('highlight');
});

我也看了document.stylesheets和看似古老的和特定于浏览器的:

  document.styleSheets[0].insertRule("p{font-size: 20px;}", 0)

但是我找不到任何关于编程生成的参考:

  @media screen and (min-width:400px)

您可以更新现有的<style>元素(或创建一个)textContent来包含该规则,这将使其在给定的上下文中有效。

document.querySelector('style').textContent +=
    "@media screen and (min-width:400px) { div { color: red; }}"
http://jsfiddle.net/vfLS3/

我是这样用的。这允许在文档

中更新叠底样式HTML:

<style class="background_image_styles">
</style>
在JS

$(".background_image_styles").text("@media (min-width: 1200px) {.user_background_image{background-image: url('https://placehold.it/1200x300');}}");

对于一般用途,您可以将样式表附加到document.head。然后你可以在其中添加任何你想要的mod—-包括媒体查询。因为它是document.head中的最后一个样式表,所以它覆盖了之前的任何CSS规则。

香草JavaScript:

    let style = document.getElementById('custom-styles');
    if (!style) {
      style = document.createElement('style');
      style.id = "custom-styles";
      document.head.appendChild(style);
    }
    style.innerHTML =
      "@media screen and (min-width:400px) {...}";

我更喜欢这种变体-附加在头部部分的末尾:

$('<style/>', {
    text: '@media print { @page { margin: 10 20 20 10; } body { margin: 0.5cm; }}',
    appendTo: win.document.head
})