问题
I am currently building a web app where I need to randomly generate text content and switch its color every time a button is clicked.
At the moment, I'm trying to add some kind of animation to it, and here's what I'd like to obtain each time the button is clicked:
- The random class is added
- The div pops up from the bottom of the page with its opacity increasing
I prepared a simplified JSFiddle to illustrate my point below.
Example
http://jsfiddle.net/cdacx0tn/11/
var color = ["blue", "purple", "green"];
$("#try-me").click(function() {
var colorClass = color[Math.floor(Math.random()*color.length)];
$("#content")
.removeClass()
.addClass(colorClass)
.animate({
"margin-top": "50px",
"opacity": "1"
}, 700);
});
I managed to get this done when the button is clicked once but I can't figure out how to do this each time it is clicked.
I want to add that I'm not a professional developper so please be indulgent.
Thanks for your help.
回答1:
Set the CSS of the element before animating it, making sure it's back at it's initial position with marginTop and can't be seen using opacity.
Add a stop() in their to prevent animations being queued and there you have it:
var color = ["blue", "purple", "green"];
$("#try-me").click(function() {
var colorClass = color[Math.floor(Math.random()*color.length)];
$("#content")
.css({opacity:0,marginTop:200})
.removeClass()
.addClass(colorClass)
.stop(true,false)
.animate({
"margin-top": "50px",
"opacity": "1"
}, 700);
});
JSFiddle
Documentation:
- css()
- stop()
回答2:
try
var color = ["blue", "purple", "green"];
$("#try-me").click(function() {
var colorClass = color[Math.floor(Math.random()*color.length)];
$("#content").css({ "margin-top": "200px", "opacity": "0"}); // reset the margin and opacity value
$("#content")
.removeClass()
.addClass(colorClass)
.animate({
"margin-top": "50px",
"opacity": "1"
}, 700,function(){
});
});
DEMO
回答3:
Re initialize the margin-top of #content to 200px after animation :
$("#content").css("margin-top","200px");
DEMO HERE
来源:https://stackoverflow.com/questions/25283571/jquery-animate-on-click-multiple-times