使用javascript或jQuery生成CSS媒体查询
是否可以使用Javascript或jQuery动态创建完整的媒体查询规则?
我使用了大量的媒体查询来使用内联CSS,导入和链接文件来定位通用视口和特定设备/屏幕:
@media screen and (min-width:400px) { ... } @import url(foo.css) (min-width:400px);
我可以使用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)
直接或以任何forms从javascript。
您只需更新现有的
元素(或创建一个) textContent
即可包含该规则,这将使其在给定的上下文中生效。
document.querySelector('style').textContent += "@media screen and (min-width:400px) { div { color: red; }}"
http://jsfiddle.net/vfLS3/
我用这种方式。 这允许更新文档中的多个样式
在HTML中:
在JS中
$(".background_image_styles").text("@media (min-width: 1200px) {.user_background_image{background-image: url('https://placehold.it/1200x300');}}");