且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用jQuery延迟更改CSS属性

更新时间:2022-10-21 22:08:36

您可以使用 queue 功能

  $(div)
.fadeOut()
.delay(500)
$ .queue(function(){
$(this).css(background-color,red)。dequeue();
})
.fadeIn();

请注意回调中的 dequeue 这是告诉jQuery继续处理队列中的下一个事情。


How can i use jQuery to change the CSS attributes of a HTML element with delay.

Imagine this scenario. I have a div with bg color blue. I want it to fade out and when it fades back in i want the bg color to be red.

I tried this.

$("div").fadeOut().delay(500).css("background-color","red").fadeIn();

While fading out the div already changes the color to red before it fades in. It does not follow the sequence of chained events. How can I make this happen in one single line.

You can have any function participate in the animation queue using the queue function:

$("div")
    .fadeOut()
    .delay(500)
    .queue(function() {
        $(this).css("background-color","red").dequeue();
    })
    .fadeIn();

Note the dequeue call within the callback, which is what tells jQuery to continue with the next thing in the queue.