延迟后使用jQuery添加类 [英] Add a class using jQuery after a delay

查看:85
本文介绍了延迟后使用jQuery添加类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当单击一个元素时,我想向body元素添加一个类,但是会有一点延迟. 因此,单击element1,然后在0.5秒后,为主体指定了一个新类.

When an element is clicked, I want to add a class to the body element, but with a slight delay. So, element1 is clicked, then after .5 seconds, the body is a given a new class.

我一直在使用它,在某种程度上...

I was using this which works to an extent...

$('.element1').click(function() {
    $('body').delay(500).queue(function(){
        $(this).addClass('left-bg')
    });
});

但是,我还有另一个click事件,该事件从正文中删除了这个left-bg类.

However, I have another click event which removes this left-bg class from body.

$('.another-element').click(function() {
    $('body').removeClass('left-bg');
});

但是下次单击.element1时,它根本不会将left-bg类应用于身体.

But then the next time .element1 is clicked, it doesn't apply the left-bg class to the body at all.

希望如此.有人可以帮助我解决这个问题或提出其他解决方法吗?

Hope that makes sense. Can anybody help me with this or suggest another way of going about it?

推荐答案

清除队列:

演示

$('.element1').click(function() {
    $('body').delay(500).queue(function(){
        $(this).addClass('left-bg').clearQueue();
    });
});

$('.another-element').click(function() {
    $('body').removeClass('left-bg');
});

这篇关于延迟后使用jQuery添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆