在任何时候只动画一个项目

时间:2014-07-17 10:10:11

标签: jquery jquery-animate

我点击动画五个框。他们基本上起伏不定。任何时候只有一个项目或框应该动画。这很好,直到您多次单击多个框,然后行为变得不稳定。

我在http://jsfiddle.net/fLmt6/9/

创建了一个演示链接

以下代码负责反弹动画

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);
}

2 个答案:

答案 0 :(得分:2)

1)首先,将事件委托给父元素。在这里,我将使用正文,因为我不知道更广泛的HTML的结构。事件委托通常是一个很好的建议,并带来一些好处,一个是你可以在事件触发时过滤元素,而不是在注册时过滤元素。这导致我...

2)添加一个过滤器,忽略已经设置动画的任何框的点击次数。

所以改变

var item = $(".items ul li a");
item.click(function () {

$('body').on('click', '.items li:not(:animated) a', function() {

答案 1 :(得分:0)

您可以添加新变量,如果元素已设置动画,则会检查该变量。你需要动画两次 - TOP,然后是BOTTOM。所以我编辑了你的代码。

变量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);
}

});

<强> JSFiddle here

相关问题