等到scrollTo完成后再运行命令

ger*_*lol 2 javascript angularjs

我有一个 AngularJS 应用程序,并且有一个平滑滚动指令来强制页面滚动到底部。我希望该命令仅在滚动完成后运行。您可以看到,此时我运行滚动功能,然后运行$('#comment-input').focus();以聚焦于一个元素。我想更改它,以便仅在滚动运行。我知道我需要实施 acallback但我不知道在哪里实施它。

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

        };

    }]);

}());
Run Code Online (Sandbox Code Playgroud)

jon*_*dev 5

我建议创建一个返回承诺并避免循环/计时器的函数。然后你可以像这样访问该函数:

    smoothScroll(element).then(() => {
      //Execute something when scrolling has finished
    });
Run Code Online (Sandbox Code Playgroud)

smoothScroll函数可以这样定义,而不需要使用很多计时器(实际定义的计时器只是为了reject()保证滚动由于某种原因(例如用户交互)失败):

function smoothScroll(elem, offset = 0) {
  const rect = elem.getBoundingClientRect();
  let targetPosition = Math.floor(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();
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

我还在这支笔中制作了一个工作示例:https ://codepen.io/familjenpersson/pen/bQeEBX