如何阻止速度动画重复自身

时间:2017-02-01 18:57:10

标签: javascript jquery css animation velocity.js

我正在使用velocity为网站的滚动按钮设置动画。当滚动窗口时,按钮会动画改变位置,当我们再次到达顶部时,它会返回原来的位置。这是代码:

 var mustSlideRight = true;
    var mustSlideLeft = false;
    var animating = false;
    $(window).scroll(function() {

        if (animating){
            return;
        }else if (!animating){
            animating = true;
            var scrolledHeight = ($(window).scrollTop());

            if (scrolledHeight > 2 && mustSlideRight)  {

                $(".scrollButton")
                    .velocity({width: "55px", height: "55px"}, {duration: 200, easing: "ease-in-out"})
                    .velocity({width: "0px", height: "0px", opacity: "0"}, {duration: 80, easing: "ease-in-out"})
                    .velocity({left: "95%", backgroundPosition: "-50px"}, {duration: 1})
                    .velocity({width: "55px", height: "55px", opacity: "1"}, {duration: 80, easing: "ease-in-out"})
                    .velocity({width: "50px", height: "50px"}, {duration: 150, complete: function(){animating = false;}, easing: "ease-in-out"});
                mustSlideRight = false;
                mustSlideLeft = true;
            }
            else if (scrolledHeight < 10 && mustSlideLeft) {

                $(".scrollButton")
                    .velocity({width: "55px", height: "55px"}, {duration: 200, easing: "ease-in-out"})
                    .velocity({width: "0px", height: "0px", opacity: "0"}, {duration: 80, easing: "ease-in-out"})
                    .velocity({left: "49%", backgroundPosition: "0px"}, {duration: 1})
                    .velocity({width: "55px", height: "55px", opacity: "1"}, {duration: 80, easing: "ease-in-out"})
                    .velocity({width: "50px", height: "50px"}, {duration: 150, complete: function(){animating = false;}, easing: "ease-in-out"});
                mustSlideLeft = false;
                mustSlideRight = true;
            }
        }
    });

按钮的背景图像是精灵。

问题是动画来回多次运行。下来它运行三次,然后返回它运行5-6次。我认为我在编写代码的过程中存在一个问题,但是我无法弄明白。有什么想法吗?

修改

@mattmokary:我做了你提出的建议,但事情变得更糟,尽管我觉得这就是方法。但是我几乎可以肯定我的代码中有错误。动画根本没有开始。

{{1}}

2 个答案:

答案 0 :(得分:0)

向下滚动页面时,会触发许多scroll个事件。每个事件都会调用此函数一次,动画排队等待。

要修复此问题,请添加一个表示动画已在运行的标记,并且在该标记为true时不再运行任何动画。类似的东西:

var animating = false;

$(window).scroll(function () {
     if (animating) {
         return;
     }

     // ...
});

当您执行动画时,您还必须设置animating = true,并在动画完成设置animating = false后将回调传递给力度以运行。

答案 1 :(得分:0)

好吧,这比我想象的容易得多。我只是更改了if语句中的参数,只触发动画到非常特定的点,动画不重复;)

select customers.CNAME, employees.ENAME from customers 
inner join orders on customers.CNO = orders.CNO
inner join employees on orders.ENO = employees.ENO;