Jquery 一次仅为一个项目设置动画
我正在为单击的五个框设置动画。它们基本上是上下波动的。一次只能对一个项目或框设置动画。这很好,直到您快速单击多次多个框,行为才会变得不稳定 我在这里创建了一个演示链接 下面的代码负责反弹动画Jquery 一次仅为一个项目设置动画,jquery,jquery-animate,Jquery,Jquery Animate,我正在为单击的五个框设置动画。它们基本上是上下波动的。一次只能对一个项目或框设置动画。这很好,直到您快速单击多次多个框,行为才会变得不稳定 我在这里创建了一个演示链接 下面的代码负责反弹动画 var itemActive = $(".items li.active"); var indicator = 1; bounceItem(); function bounceItem() { bounceInterval
var itemActive = $(".items li.active");
var indicator = 1;
bounceItem();
function bounceItem() {
bounceInterval = setInterval(function () {
if (indicator === 1) {
indicator = -1;
} else {
indicator = 1;
}
$(".items li").not(".active").stop().css({
top: "11px"
});
itemActive.animate({
top: "+=" + (indicator * 11)
}, 400);
}, 400);
}
1) 首先,将事件委托给父元素。在这里,我将使用正文,因为我不知道更广泛的HTML的结构。一般来说,事件委派是一个很好的建议,它有几个好处,其中一个好处是可以在事件触发时过滤元素,而不是在事件注册时过滤元素。这让我想到
2) 添加忽略已设置动画的任何框的单击的过滤器
所以改变
var item = $(".items ul li a");
item.click(function () {
到
可以添加新变量,该变量将检查元素是否已设置动画。您需要设置两次动画-顶部,然后底部。所以我编辑了你的代码 变量
animated
在动画之前设置为0
,然后在元素在顶部反弹时设置为1
,然后在元素反弹到底部时设置为2
,然后停止反弹
var item = $(".items ul li a");
item.click(function () {
$(this).parent().siblings().removeClass("active");
$(this).parent().siblings().css({
top: "11px"
});
if (!$(this).parent().hasClass("active")) {
$(this).parent().fadeOut("fast", function () {
$(this).addClass("active").fadeIn("slow");
var itemActive = $(".items li.active");
var indicator = 1;
var animated = 0;
bounceItem();
function bounceItem() {
bounceInterval = setInterval(function () {
if (indicator === 1) {
indicator = -1;
} else {
indicator = 1;
}
$(".items li").not(".active").stop().css({
top: "11px"
});
if(animated != 2) {
itemActive.animate({
top: "+=" + (indicator * 11),
times: 1
}, 400);
animated += 1;
}
}, 400);
}
});
clearInterval(bounceInterval);
}
});
这稍微改变了功能。盒子应该一直弹跳..直到你点击另一个。但你的弹跳过一次我以为这就是你想要的。。呃,对不起,我的朋友bad@gables20有时两个盒子同时跳。尽管我优化了代码并用
bounceInterval
修复了错误:嗯,不,我弄坏了一些东西。需要注意这是因为你在哪里设置了你的跳出时间间隔。我更新了你的代码@gables20 yea,我已经把它放在那里并重新放进去了,但有时仍然有problems@Regent从我这边来看,你看到了什么样的问题,到目前为止,这只是一时冲动。@gables20在我的小提琴版本中,我仍然同时得到两个弹跳框。也许最好在上一个正在设置时禁止单击。。。或者,问题仍然存在于设置和清除间隔中
var item = $(".items ul li a");
item.click(function () {
$(this).parent().siblings().removeClass("active");
$(this).parent().siblings().css({
top: "11px"
});
if (!$(this).parent().hasClass("active")) {
$(this).parent().fadeOut("fast", function () {
$(this).addClass("active").fadeIn("slow");
var itemActive = $(".items li.active");
var indicator = 1;
var animated = 0;
bounceItem();
function bounceItem() {
bounceInterval = setInterval(function () {
if (indicator === 1) {
indicator = -1;
} else {
indicator = 1;
}
$(".items li").not(".active").stop().css({
top: "11px"
});
if(animated != 2) {
itemActive.animate({
top: "+=" + (indicator * 11),
times: 1
}, 400);
animated += 1;
}
}, 400);
}
});
clearInterval(bounceInterval);
}
});