2013-08-21 23 views
0

我在當前項目中使用enquire.js。我用它來CSS類在小屏幕上添加幾個元素大屏幕,並刪除這些類:爲多個addClass創建函數,與enquire.js一起使用

enquire.register("screen and (min-width: 48.0625em)", { 
    match : function() { 
     // absolute position for "bubble" lists 
     $('.bubbles').addClass('structure'); 
     $('.structure li:nth-child(1)').addClass('s1'); 
     $('.structure li:nth-child(2)').addClass('s2'); 
     $('.structure li:nth-child(3)').addClass('s3'); 
     $('.structure li:nth-child(4)').addClass('s4'); 
     $('.structure li:nth-child(5)').addClass('s5'); 
     $('.structure li:nth-child(6)').addClass('s6'); 
     $('.structure li:nth-child(7)').addClass('s7'); 
     $('.structure li:nth-child(8)').addClass('s8'); 
     $('.structure li:nth-child(9)').addClass('s9'); 
    }, 

    unmatch : function() { 
     $('.bubbles').removeClass('structure'); 
     $('.structure li:nth-child(1)').removeClass('s1'); 
     $('.structure li:nth-child(2)').removeClass('s2'); 
     $('.structure li:nth-child(3)').removeClass('s3'); 
     $('.structure li:nth-child(4)').removeClass('s4'); 
     $('.structure li:nth-child(5)').removeClass('s5'); 
     $('.structure li:nth-child(6)').removeClass('s6'); 
     $('.structure li:nth-child(7)').removeClass('s7'); 
     $('.structure li:nth-child(8)').removeClass('s8'); 
     $('.structure li:nth-child(9)').removeClass('s9'); 
    } 
}); 

我們有了成爲一個簡寫本。我本來以爲我可以創建一個功能是這樣的:

$(.'bubbles').each(function() { 
    // add all the classes here 
} 

那麼這將是詢價。unmatch功能可逆式。這可能嗎...?

回答

0

可以使用each回調的索引屬性來切換你的類:

enquire.register("screen and (min-width: 48.0625em)", { 
    match: function() { 
     // absolute position for "bubble" lists 
     $('.bubbles').addClass('structure'); 
     $('.structure li').each(function (index) { 
      $(this).toggleClass('s' + (index + 1)); 
     }); 
    }, 

    unmatch: function() { 
     $('.structure li').each(function (index) { 
      $(this).toggleClass('s' + (index + 1)); 
     }); 
     $('.bubbles').removeClass('structure'); 
    } 
}); 
+0

完美。謝謝! –

相關問題