0

我在当前项目中使用enquire.js。我正在使用它将 css 类添加到大屏幕的几个元素中,并在较小的屏幕上删除这些类:

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查询功能中是可逆的。这可能吗...?

4

1 回答 1

0

您可以使用each回调的 index 属性来切换您的类:

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');
    }
});
于 2013-08-21T14:47:09.790 回答