简体   繁体   English

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

[英]Generating CSS media queries with javascript or jQuery

Is it possible to create full media query rules on the fly using Javascript or jQuery?是否可以使用 Javascript 或 jQuery 即时创建完整的媒体查询规则?

I've used numerous media queries to target generalised viewports and specific devices/screens using inline CSS, imports and linked files:我已经使用大量媒体查询来定位通用视口和特定设备/屏幕,使用内联 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" />

I can add/remove classes using jQuery:我可以使用 jQuery 添加/删除类:

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

I've also look at document.stylesheets and the seemingly archaic and browser-specific:我还查看了document.stylesheets和看似过时且特定于浏览器的:

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

But I can't find any reference to programatically generating:但我找不到任何以编程方式生成的参考:

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

from javascript directly or in any form.从 javascript 直接或以任何形式。

You can just update an existing <style> element (or create one) textContent to contain the rule, which will make it effective in the given context.您可以更新现有的<style>元素(或创建一个) textContent以包含规则,这将使其在给定的上下文中有效。

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

http://jsfiddle.net/vfLS3/ http://jsfiddle.net/vfLS3/

I use this way.我用这种方式。 This allows to update multiply styles in document这允许更新文档中的多种样式

in HTML:在 HTML 中:

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

in JS在JS中

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

For general purpose use, you can append a style sheet to document.head .对于一般用途,您可以将样式表附加到document.head Then you can put any mods in there you want -- including media queries.然后你可以把任何你想要的 mods 放在那里——包括媒体查询。 Since it's the final style sheet in document.head , it overrides any prior CSS rules.由于它是document.head的最终样式表,因此它会覆盖任何先前的 CSS 规则。

Vanilla JavaScript:原生 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) {...}";

I prefer this variant - appending to the end of the head section:我更喜欢这个变体 - 附加到头部部分的末尾:

$('<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