等到scrollTo完成后再运行命令

时间:2015-06-09 08:55:55

标签: javascript angularjs

我有一个AngularJS应用程序,我有一个平滑的滚动指令来强制页面滚动到底部。我希望命令只在滚动完成后运行。您可以看到,此时我运行滚动功能,然后运行$('#comment-input').focus();以关注元素。我想更改它,所以这只是在滚动后运行。我知道我需要实现一个callback,但我无法弄清楚在哪里实现它。

(function() {

    var app = angular.module('myApp');

    app.service('anchorSmoothScroll', function(){

        this.scrollTo = function(eID) {

            // This scrolling function 
            // is from http://www.itnewb.com/tutorial/Creating-the-Smooth-Scroll-Effect-with-JavaScript

            var startY = currentYPosition();
            var stopY = elmYPosition(eID);
            var distance = stopY > startY ? stopY - startY : startY - stopY;
            if (distance < 100) {
                scrollTo(0, stopY); return;
            }
            var speed = Math.round(distance / 100);
            if (speed >= 20) speed = 20;
            var step = Math.round(distance / 25);
            var leapY = stopY > startY ? startY + step : startY - step;
            var timer = 0;
            if (stopY > startY) {
                for ( var i=startY; i<stopY; i+=step ) {
                    setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
                    leapY += step; if (leapY > stopY) leapY = stopY; timer++;
                } return;
            }
            for ( var i=startY; i>stopY; i-=step ) {
                setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
                leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
            }

            function currentYPosition() {
                // Firefox, Chrome, Opera, Safari
                if (self.pageYOffset) return self.pageYOffset;
                // Internet Explorer 6 - standards mode
                if (document.documentElement && document.documentElement.scrollTop)
                    return document.documentElement.scrollTop;
                // Internet Explorer 6, 7 and 8
                if (document.body.scrollTop) return document.body.scrollTop;
                return 0;
            }

            function elmYPosition(eID) {
                var elm = document.getElementById(eID);
                var y = elm.offsetTop;
                var node = elm;
                while (node.offsetParent && node.offsetParent != document.body) {
                    node = node.offsetParent;
                    y += node.offsetTop;
                } return y;
            }

        };

    });

    app.controller('TextareaController', ['$scope','$location', 'anchorSmoothScroll',
    function($scope, $location, anchorSmoothScroll) {

        $scope.gotoElement = function (eID){
          // set the location.hash to the id of
          // the element you wish to scroll to.
          $location.hash('bottom-div');

          // call $anchorScroll()
          anchorSmoothScroll.scrollTo(eID);

          $('#comment-input').focus();

        };

    }]);

}());

3 个答案:

答案 0 :(得分:2)

获取anchorSmoothScroll.scrollTo返回一个promise(使用$ q),然后在promise完成后重点关注。 Read here了解有关$ q的更多信息。

anchorSmoothScroll.scrollTo(eID)
     .then(function() {
          $('#comment-input').focus();
     })
编辑:您的代码失败了,因为您正在setTimeout中执行scrollTo,而您必须解决您的承诺。现在,下一个问题是有多个setTimeout(因为它在for循环中),所以会有很多的promise,而$ q.all会帮助你。

我为你设置了一个plunker,我已经更新了其中一条执行路径......看看here。在控制台窗口中,滚动完成后,您将看到聚焦是打印机。为了说明这一点,我将setTimeout间隔硬编码为2秒。我希望有所帮助。

答案 1 :(得分:0)

当你使用

到达底部时,你最终可以尝试绑定一个监听器
elm.on('scroll', function() {
      if(elm[0].scrollTop === elm[0].scrollHeight)
       $('#comment-input').focus();
    });

答案 2 :(得分:0)

我建议创建一个返回承诺并避免循环/计时器的函数。然后您可以访问如下功能:

smoothScroll(element).then(() => {
  //Execute something when scrolling has finished
}

可以像这样定义smoothScroll函数,而无需使用很多计时器(实际定义的计时器仅用于reject(),如果由于某些原因(例如用户交互)而滚动失败):

function smoothScroll(elem, offset = 0) {
  const rect = elem.getBoundingClientRect();
  let targetPosition = rect.top + self.pageYOffset + offset;
  window.scrollTo({
    top: targetPosition,
    behavior: 'smooth'
  });

  return new Promise((resolve, reject) => {
    const failed = setTimeout(() => {
      reject();
    }, 2000);

    const scrollHandler = () => {
      if (self.pageYOffset === targetPosition) {
        window.removeEventListener("scroll", scrollHandler);
        clearTimeout(failed);
        resolve();
      }
    };
    if (self.pageYOffset === targetPosition) {
      clearTimeout(failed);
      resolve();
    } else {
      window.addEventListener("scroll", scrollHandler);
      elem.getBoundingClientRect();
    }
  });
}

我在这支笔上也做了一个实际的例子:https://codepen.io/familjenpersson/pen/bQeEBX