3

假设我想动态添加与媒体条件相关的 CSS 规则。例如,如下所示:

@media only screen and (min-device-width : 500px){
    .someClass: {
        color: blue;
    }
}

一个合乎逻辑的步骤是使用 JavaScript 检查媒体查询的有效性并在测试通过时插入规则。如下所示:

if(matchMedia(only screen and (min-device-width : 500px))){
    $('.someClass').css('color', 'blue');
}

缺点是规则不会响应。如果我改变屏幕尺寸,蓝色不会相应改变。我可以为屏幕尺寸变化添加一个监听器,但我认为这有点矫枉过正。

我的问题是:有没有办法通过 Javascript 或 JQuery添加响应规则?

4

2 回答 2

4

你想听听enquire.js

enquire.register("screen and (max-width:1000px)", {

    match : function() {},      // REQUIRED
                                // Triggered when the media query transitions 
                                // *from an unmatched state to a matched state*

    unmatch : function() {},    // OPTIONAL
                                // If supplied, triggered when the media query transitions 
                                // *from a matched state to an unmatched state*.

    setup : function() {},      // OPTIONAL
                                // If supplied, a one-time setup function 
                                // triggered when the handler is first registered.                           

    deferSetup : true,          // OPTIONAL, defaults to false
                                // If set to true, defers execution the setup function until
                                // the media query is first matched. Setup is still triggered just once.

    destroy : function() {}     //OPTIONAL
                                // If supplied, triggered when a hander is unregistered (covered later). 
                                // Enables you to provide lifecycle to responsive widgets. 
                                // Put cleanup logic here.

}).listen(); // More on this next

[来自文档]

编辑:如果您想通过 js 添加纯 CSS 规则 [不依赖于侦听器],我认为这是不可能的。

于 2013-02-08T10:54:08.287 回答
1

您可以使用 responsive.js 库呈现动态 css。它可以帮助您动态地定义将在客户端呈现为本机 css 的响应规则。它使用流畅的界面编程风格,并且在不支持媒体查询的情况下也可以工作(动态呈现当前有效规则)。

例如,您可以将 width 属性定义为:

r$.breakpoints(320,767,1280);
r$.set('width','px').values(100,300,1500).linearInt().applyTo('.class'); 

更多信息、下载和示例,请访问:

http://www.responsivejs.com

于 2013-03-09T07:50:43.660 回答