Generating CSS media queries with javascript or jQuery

后端 未结 3 1770
再見小時候
再見小時候 2020-12-08 03:24

Is it possible to create full media query rules on the fly using Javascript or jQuery?

I\'ve used numerous media queries to target generalised viewports and spec

相关标签:
3条回答
  • 2020-12-08 03:48

    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.

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

    http://jsfiddle.net/vfLS3/

    0 讨论(0)
  • 2020-12-08 03:56

    For general purpose use, you can append a style sheet to document.head. Then you can put any mods in there you want -- including media queries. Since it's the final style sheet in document.head, it overrides any prior CSS rules.

    Vanilla 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) {...}";
    
    0 讨论(0)
  • 2020-12-08 03:59

    I use this way. This allows to update multiply styles in document

    in HTML:

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

    in JS

    $(".background_image_styles").text("@media (min-width: 1200px) {.user_background_image{background-image: url('https://placehold.it/1200x300');}}");
    
    0 讨论(0)
提交回复
热议问题