繁体   English   中英

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

[英]Generating CSS media queries with javascript or jQuery

是否可以使用 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)

从 javascript 直接或以任何形式。

您可以更新现有的<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 然后你可以把任何你想要的 mods 放在那里——包括媒体查询。 由于它是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
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM