2013-02-08 51 views
3

讓我們假設我想動態添加與媒體條件相關的CSS規則。例如,類似以下內容:使用Javascript或JQuery插入響應式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添加響應規則?

+2

jQuery是JavaScript的 –

+0

檢查它是否對您有所幫助的http:// stackoverflow.com/questions/14068024/how-to-change-responsive-style-using-jquery –

回答

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規則[不依靠聽衆]我想這不可能。

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