问题
I had fantastic help from David on this post How to reset css before repeating sequence but there wasn't enough room in comments to ask all my questions. David set my JQuery right and also rewrote most of it because I was heading in the wrong direction What I have now is exactly what I want, Text appears on the right, slides over to the left, pauses and fades. A new line of text does the same thing and I can have as many lines as I want.
I would like to understand what is happening here, I'm a complete Noob with JQuery. Here is a jsfiddle of it working - http://jsfiddle.net/Bf49z/13/ - I have rearranged the lines so they make more sense to me. Here are the questions that wouldn't fit in the comments -
What is hard to understand is why the animation is stopped, before it’s started.
$elements.eq(index).stop() .animate({
I assume it stops the animation at the second, third, fourth etc repeats?
Then
.animate({"opacity": "1", //Animate opacity to opaque
"left": "6px" //Animate left to 6px
}, 1000,
Makes it visible and moves it to the left, taking one second?
I understand
$(this).delay(3000) .animate({ //Wait 3000ms
Then is this next line a way of fading by changing opacity over 1 second?
.animate({ "opacity": "0" //Animate opacity to transparent
}, 1000,
Then the next 2 lines reset the css?
function(){ //After animation
$(this).css("left", "400px"); //Reset left
Thanks again for your help, hope you don’t mind the questions. Rob
回答1:
The call to .stop()
will stop any animation that is in-progress for the element. But since there shouldn't be any, it is unnecessary in your case. It is often used when animations are triggered by mouse events. In such a case, you may need to stop an animation that is in-progress before starting a new one.
The answers to your other questions are all "yes", but .delay()
applies to the animation queue, so you do not have to put it in the "complete" function.
Therefore you could shorten your code to:
(function animate(index) {
$elements.eq(index)
.animate({ opacity: '1', left: '6px' }, 1000)
.delay(3000)
.animate({ opacity: '0' }, 1000, function() {
$(this).css({ left: '400px' });
animate((index + 1) % $elements.length);
});
})(0);
jsfiddle
回答2:
the .stop() function here is just for decoration, it does not change anything, therefore if can easily be cut.
exactly
exactly
exactly
来源:https://stackoverflow.com/questions/22291054/trying-to-understand-a-jquery-routine