0

I've looked at other examples but can't find one like this:

What I'm trying to do: Have the '.Wrapper' element change background color when the element '.box1' is clicked, then after delay(x) have the .Wrapper revert to its prior state. (The background color is added from a class called '.clicked1')

The code I have right now adds '.clicked1', but I can't figure out how to remove the class via delay.

Any help?

$(function () {
$('.box1').click(function () {
    $('.Wrapper').addClass('clicked1')
});
});
4

3 回答 3

6

Try with .delay()

$(function () {
    $('.box1').click(function () {
        $('.Wrapper').addClass('clicked1').stop().delay(2000).queue(function () {
            $(this).removeClass('clicked1')
        })
    });
});

Demo: Fiddle

or using setTimeout()

$(function () {
    $('.box1').click(function () {
        $('.Wrapper').addClass('clicked1');
        setTimeout(function(){
            $('.Wrapper').removeClass('clicked1');
        }, 2000)
    });
});

Demo: Fiddle

于 2013-09-17T16:22:24.600 回答
2

Don't use delay but setTimeout :

$('.box1').click(function () {
    $('.Wrapper').addClass('clicked1')
    setTimeout(function(){
        $('.Wrapper').removeClass('clicked1')
    }, 2000);
});
于 2013-09-17T16:22:22.093 回答
0

First, store a reference to your timer and secondly, cache $(this)

(function() {
 var timer;
 $('.box1').click(function() {
   var el = $(this);

   el.addClass('clicked1');

   clearTimeout(timer);
   timer = setTimeout(function() {
       el.removeClass('clicked1');
   });

 });
}());
于 2013-09-17T16:40:17.607 回答