如何使jQuery .stop()用于切换动画

时间:2016-02-10 18:56:42

标签: jquery angularjs

我刚刚制作了我的项目演示。我强烈建议您检查我的JSFiddle,看看到底发生了什么。

我也把代码放在这里。

HTML:

<div ng-app="slideApp" ng-controller="slideCtrl">
    <input type="button" value="Slide Down" ng-click="toggleSlide()">
    <br>
    <div style="display:none" slide-toggle>
        <a class="slide hide-slide" href="#">Slide Up</a>
    </div>
</div>

AngularJs:

var app = angular.module("slideApp", []);

app.controller("slideCtrl", function($scope, $timeout) {
    $scope.slide = false;
    $scope.toggleSlide = function() {
        $scope.slide = true;
    }
});

app.directive("slideToggle", function() {
    return {
        restrict: "A",
        link: function(scope, element) {
            scope.$watch("slide", function(newVal) {
                if (newVal) {
                    $(element).slideDown().delay(2000).slideUp();
                } 
                scope.slide = false;
            })

            $(element).find(".hide-slide").on("click", function() {
                $(element).stop(true, true).slideUp();
            })
        }
    }
})

我的问题是:

当&#34;向下滑动&#34;单击,面板将向下滑动并持续2秒,然后自动向上滑动。

现在这样做: 1.重复点击&#34;向下滑动&#34;显示面板,然后单击&#34;向上滑动&#34;立即隐藏面板; 2.完成上述操作几次后,单击&#34;向下滑动&#34;立即(不要点击&#34;向上滑动&#34;这次),您将看到面板向下滑动并快速向上滑动,而面板应该在延迟2秒后向上滑动。

我知道为什么这不起作用(jQuery .Stop() documentation)。

  

如果在同一个元素上调用多个动画方法,则   以后的动画放置在元素的效果队列中。   这些动画直到第一个动画完成才会开始。什么时候   调用.stop(),队列中的下一个动画立即开始。

但有没有人有解决方案让面板在延迟2秒后滑动?如果你有一个解决方案让它工作并更新我的JSFiddle,我真的很感激。非常感谢!

2 个答案:

答案 0 :(得分:0)

我认为你只需要在第16行添加另一个stop()

$(element).stop(true, true).slideDown().delay(2000).slideUp();

Updated JSFiddle

答案 1 :(得分:0)

There's two problems here. The first is that repeatedly clicking slideDown causes the queue to build up. The fix is easy, add .stop(true,true) to it. This will keep it open for longer if you repeatedly click slide down, and then close 2 seconds after the last time it is clicked. (@TedWhitehead showed this in his answer)

$ python your_code.py things to search for

Next, when you click slideUp, you don't need to clear the queue since at the end of the queue you're going to slide it up anyway. Instead, just jump to the end of the current animation (which would be the delay,) and don't slide it back up.

$(element).stop(true,true).slideDown().delay(2000).slideUp();

It simply ends the delay and continues on with the next thing in the queue, the slideUp. https://jsfiddle.net/yxdqtm79/42/