Please see Matt's answer to this question. He says that .delay()
is confusing to most people, and he gives the following example:
$('#foo').hide().delay(2000).slideDown().text('Hello!').delay(2000).hide();
See here for the fiddle. Could somebody explain the behaviour of that line of code?开发者_Python百科
Only certain parts of jQuery's code can be pushed off with .delay()
-- hide()
and text()
are not a part of that group.
So basically what the code is doing is (not really doing this, this is just a sketch):
setTimeout(function(){
$('#foo').slideDown();
}, 2000);
$('#foo').hide().text('Hello!').hide();
So that is why the slideDown()
seems to happen last.
The reason it misbehaves has already been explained. To get the desired behaviour, use queue
:
$('#foo')
.hide()
.delay(2000)
.slideDown()
.queue(function() {
$(this).text('Hello!').dequeue();
})
.delay(2000)
.queue(function() {
$(this).hide().dequeue();
});
The delay
places a delay (no-effect animation) in the animation queue, so it only affect other animations. Chaining hide
after delay
doesn't delay the hide
, it still happens right away.
If you divide the methods into the ones that affect the element at once, and the methods that starts animations, you get this code that does the same:
$('#foo').hide().text('Hello!').hide(); // set text and hide twice
$('#foo').delay(2000).slideDown().delay(2000); // wait, slide, wait and do nothing
精彩评论