改进这个连续的 jQuery 动画
我刚刚在 jQuery 中创建了一个简单、连续的 反弹效果 但我觉得代码不是所有这些都经过优化,并且正在寻求改进。
var $square = $("#square");
bounce();
function bounce() {
$square.animate({
top: "+=10"
}, 300, function() {
$square.animate({
top: "-=10"
}, 300, function() {
bounce();
})
});
}
$square.hover(function() {
jQuery.fx.off = true;
}, function() {
jQuery.fx.off = false;
});
我所做的基本上就是创建一个动画,将 +10 添加到元素的顶部坐标,并且作为回调函数,我从顶部坐标中减去 10。
这会创建一个(几乎平滑的)弹跳效果,但我感觉还可以改进。
此外,我想在 mouseenter
上停止动画,并让它在 mouseleave
上继续。
stop(true, true)
不起作用,dequeue()
也不起作用,所以我求助于使用 jQuery.fx.off 关闭所有动画效果= true
(愚蠢,不是吗?)如果
有任何有关如何优化的反馈,我将不胜感激。
这是一个 jsFiddle。
编辑:我刚刚意识到 jQuery 在禁用和重新启用效果时开始抛出太多递归
错误。
提前致谢,
Marko
I've just created a simple, continuous bounce effect in jQuery but I feel the code isn't all that optimized and am looking to improve it.
var $square = $("#square");
bounce();
function bounce() {
$square.animate({
top: "+=10"
}, 300, function() {
$square.animate({
top: "-=10"
}, 300, function() {
bounce();
})
});
}
$square.hover(function() {
jQuery.fx.off = true;
}, function() {
jQuery.fx.off = false;
});
All I've done is basically created an animation that adds +10 to the top coordinate of the element, and as a callback function, I'm subtracting 10 from the top coordinate..
This creates an (almost smooth) bounce effect but I feel it can be improved.
Furthermore, I want to stop the animation on mouseenter
, and have it continue on mouseleave
.
stop(true, true)
didn't work, neither did dequeue()
so I've resorted to turning all animation effects off using jQuery.fx.off = true
(stupid, no?)
I'd appreciate any feedback on how this can be optimized.
Here's a jsFiddle.
EDIT: I've just realized that jQuery has started throwing too much recursion
errors when disabling and re-enabling the effects.
Thanks in advance,
Marko
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请尝试以下代码演示:http://jsfiddle.net/LMXPX/
编辑:我猜你的代码中多个 CallBack 函数是递归过多的原因
Please try the below code Demo : http://jsfiddle.net/LMXPX/
Edit : I guess in your code multiple CallBack functions are the reason for too much recursion
没有太大的改进,但这是我的尝试:
Not much of an improvement but here's my attempt: