使用 javascript 或 jQuery 生成 CSS 媒体查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16050926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generating CSS media queries with javascript or jQuery
提问by nickhar
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 直接或以任何形式。
回答by Explosion Pills
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; }}"
回答by Server Izetov
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');}}");
回答by terrymorse
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.
对于一般用途,您可以将样式表附加到document.head
. 然后你可以把任何你想要的 mods 放在那里——包括媒体查询。由于它是 中的最终样式表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) {...}";