Angular:如何在滚动事件上保持重置$ timeout,否则让$ timeout完成

时间:2017-08-23 00:05:07

标签: javascript jquery html css angularjs

我正在研究一个监视滚动事件并应用CSS类的小控制器,并应用不同的CSS类。长话短说我试图让滚动条拇指在你不滚动时消失,并在你滚动时出现(如iPhone上的滚动条拇指)。

我在实施它时遇到了麻烦。我这样做的思考过程是:

1) On page load, set a $scope variable to false. 
2) Watch for a scroll event on the div I want.
3) Once the scroll event starts, set the $scope variable to true. 
4) Keep on resetting the $timeout whenever a scroll event fires.
5) In the timeout function, set the $scope variable back to false if the $timeout finishes.
6) In the HTML, set an ng-class to watch for this $scope variable.

我觉得这听起来很简单,但我在实现它时遇到了很多麻烦,而且我不确定它是否只是关于$ timeout的东西,我错过了,或者我只是想在圈子里思考还没有意识到。

这是我为它设置的控制器(实际工作的JSFiddle链接在这段代码之下):

(function () {
    'use strict';
    angular
        .module('scrollingApp')
        .controller('scrollbarController', scrollbarController);

    function scrollbarController($scope, $timeout) {
        $scope.actuallyScrolling = false;

        $scope.scrolling = function() {
            $('.container').on('scroll', function(event) {
                $scope.actuallyScrolling = true;
                console.log('before checkScroll ', $scope.actuallyScrolling);
                checkScroll();
            });
        };

        var checkScroll = function() {
            var timeoutEnded = false;
            $timeout(function() {
                if($scope.actuallyScrolling) {
                    $scope.actuallyScrolling = false;
                    console.log('inside $timeout if statement', $scope.actuallyScrolling);
                }
            }, 1000);
            console.log($scope.actuallyScrolling);
        };
        $scope.scrolling();
    }
})();

我在这里设置了一个JSFiddle(https://jsfiddle.net/hurgledurf/k5naeora/)和我迄今为止的代码(希望它是不言自明的),并且会感谢任何人可能拥有的任何帮助/见解。谢谢!

1 个答案:

答案 0 :(得分:4)

Angular of not ... To" reset"滚动超时应该这样:

var timer;
$('.container').on('scroll', function(event) {
  console.log('User is actually scrolling...');

  clearTimeout(timer);
  timer = setTimeout(function(){
    console.log('User finished scrolling.');
  },500);

});

它取代了你的代码块:

$('.container').on('scroll', function(event) {
  $scope.actuallyScrolling = true;
  console.log('before checkScroll ', $scope.actuallyScrolling);
  checkScroll();
});
相关问题