delayed addclass/remove class function not working

大憨熊 提交于 2019-11-26 22:22:13

问题


what am I doing wroing here?

$(function() {
$('ul li:nth-child(1)').addClass("go").delay(4500).removeClass("go");
$('ul li:nth-child(2)').addClass("go").delay(1500).removeClass("go");
$('ul li:nth-child(3)').addClass("go").delay(500).removeClass("go");
$('ul li:nth-child(4)').addClass("go").delay(4500).removeClass("go");
$('ul li:nth-child(5)').addClass("go").delay(1000).removeClass("go");
});

回答1:


Just to add, you can use a .queue:

$('ul li:nth-child(1)').addClass("go")
                       .delay(4500)
                       .queue(function() {
                           $(this).removeClass("go");
                           $(this).dequeue();
                       });



回答2:


.delay() is only designed to work with animations. You'll have to resort to using regular setTimeouts for what you're doing:

var li = $('ul li:nth-child(1)').addClass('go');
setTimeout(function () {
    li.removeClass('go');
}, 4500);

To make doing this to every <li> a little more pleasant, you can refactor your code like so:

$(function () {
    var delays = [4500, 1500, 500, 4500, 1000];
    $('ul li').addClass('go').each(function (i) {
        setTimeout(function (li) {
            li.removeClass('go');
        }, delays[i], $(this));
    });
});


来源:https://stackoverflow.com/questions/4954814/delayed-addclass-remove-class-function-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!