使用javascript或jQuery生成CSS媒体查询 [英] Generating CSS media queries with javascript or jQuery

查看:107
本文介绍了使用javascript或jQuery生成CSS媒体查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用Javascript或jQuery即时创建完整的媒体查询规则?



我使用了大量媒体查询来定位广义视口使用内联CSS,导入和链接文件的特定设备/屏幕:

  @media屏幕和(min-width:400px){。 ..} 
@import url(foo.css)(min-width:400px);
< link rel =stylesheettype =text / cssmedia =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:但是我找不到任何程序生成的引用:

p>

  @media screen and(min-width:400px)
解决方案

您可以直接更新现有< style> 元素(或创建一个) textContent 以包含规则,

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

http://jsfiddle.net/vfLS3/


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 specific devices/screens using inline CSS, imports and linked files:

@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:

$("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[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.

解决方案

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/

这篇关于使用javascript或jQuery生成CSS媒体查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆