gpt4 book ai didi

javascript - 观察元素位置并对 AngularJS 中的变化使用react

转载 作者:行者123 更新时间:2023-11-28 06:19:08 24 4
gpt4 key购买 nike

我正在 AngularJS 中处理一个相当复杂的 View ,但每次只有少量元素滚动到页面 View 中。因此,理想情况下,出于性能目的,我希望能够在滚动到屏幕外的元素的子元素上暂停观察者。

我正在使用的滚动条似乎通过调整其“顶部”属性来“虚拟”滚动。所以当我的标记部分向下滚动时,它看起来像这样:

<div id="mCSB_3_container" class="mCSB_container mCS_x_hidden mCS_no_scrollbar_x" style="position: relative; top: -123px; left: 0px; width: 100%;" dir="ltr">
<div id="table-1" pause-watchers></div>
<div id="table-2" pause-watchers></div>
<div id="table-3" pause-watchers></div>
</div>

因此,在我的“pauseWatchers”指令中,我尝试观察表格元素的偏移位置,并在它们超出屏幕边界时进行进一步处理。这是我到目前为止所拥有的:

app.directive('pauseWatchers', function(){
return {
link: function (scope, element) {

scope.$watch(function () {
return element.offset().top;
},
function (newValue, oldValue) {
console.log(newValue + ' : ' + oldValue);
if (newValue !== oldValue) {
//further processing goes here
}
}
);
}
}
});

观察者没有按照我需要的方式工作。基本上,它获取偏移值的唯一时间是在页面加载时以及我单击该元素时。

如何让它监视偏移值的变化?

最佳答案

很可能 watchExpression 不会被调用,因为滚动 #mCSB_3_container (以及在任何其他容器中)不会触发 $digest循环。

这意味着您应该为 #mCSB_3_container 上的滚动事件添加回调,以触发摘要周期。

类似这样的东西(可以重构为指令):

// ... code ...
angular
.element($document[0].querySelector('#mCSB_3_container'))
.on('scroll', function () {
$rootScope.$evalAsync();
});
// ... code ...

为此,我强烈建议使用 debounced function以提高性能。

TL;TR: 我发现 this library这应该对您有帮助,因为它正是您想要的。

关于javascript - 观察元素位置并对 AngularJS 中的变化使用react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35682575/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com