实时角度更新位置

Angular update position in realtime

本文关键字:位置 更新 实时      更新时间:2023-09-26

我正在尝试进行滚动检测,该检测将在滚动时更新元素的位置。

JS代码:

angular.directive('menu', ['$window', function($window){
    return function (scope, element) {
        var w = angular.element($window);
        var top = element.offset().top;
        w.bind('scroll', function () {
            adjustHeight();
        });
        function adjustHeight(){
            var newtop = top - w.scrollTop();
            if(newtop>0){
                scope.top = top - w.scrollTop();
            }else{
                scope.top = '0';
            }
        }
    };
}]);

.HTML:

<div ng-style="{'top':top}" menu></div>

只有在停止滚动后,位置才会更新。如何获取实时仓位更新?

您需要告诉 Angualar 您的更改,以便它可以应用它:

w.bind('scroll', function () {
    adjustHeight();
    scope.$apply();
});

因为 adjustheight 事件处理程序在角度范围之外运行。建议使用 scope.$apply 来表示。

此外,最好将w.scrollTop();分配给变量以提高性能。

angular.directive('menu', ['$window', function($window){
    return function (scope, element) {
        var w = angular.element($window);
        var top = element.offset().top;
        w.bind('scroll', function () {
            scope.$apply(adjustHeight); // pass the adjustheight function to scope.$apply.
        });
        function adjustHeight(){
            var scrolltop = w.scrollTop();
            var newtop = top - scrolltop;
            if(newtop>0){
                scope.top = top - scrolltop;
            }else{
                scope.top = '0';
            }
        }
    };
}]);