jQuery多次点击动画 [英] jQuery animate on click multiple times
问题描述
我目前正在构建一个Web应用程序,每次单击按钮时,我都需要随机生成文本内容并切换其颜色.
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:
- 添加了随机类
- div从页面底部弹出,其不透明度增加
我准备了一个简化的JSFiddle来说明我的观点.
I prepared a simplified JSFiddle to illustrate my point below.
示例
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.
感谢您的帮助.
推荐答案
在对元素进行动画处理之前设置其CSS,并确保使用marginTop
返回该元素的初始位置,并且不能使用opacity
看到它.
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
.
在其中添加stop()
可以防止动画排队,您可以在其中找到它:
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);
});
文档:
这篇关于jQuery多次点击动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!