gpt4 book ai didi

javascript - 使用 ng-repeat 时如何获得元素的正确高度和偏移值?

转载 作者:数据小太阳 更新时间:2023-10-29 05:38:27 24 4
gpt4 key购买 nike

我正在尝试获取列表项的偏移量和高度。一旦我有了这些,我就在父指令上调用一个函数。 最后,这将是进入 View 时进出的过渡元素。

问题:由于ng-repeat(我不知道为什么),el[0].offsetheightel[0].getBoundingClientRect().top; 值几乎是随机的;除非,我在逻辑周围包装了一个 $timeout我认为这是因为样式有时间渲染?

问题:如何在不包装 $timeout 或使用 $watch 的情况下获得准确的偏移量和高度。

HTML:

<dt  spyed ng-repeat="exp in experiences">
...
</dt>

JS:

app.directive('spyed', function () {
return {
require: '^scrollSpyer',
link: function(scope, el, attrs, ctrl) {
// this value is mostly random after the $first ng-repeat item
var offset = el[0].getBoundingClientRect().top;
// this value is also mostly randome after the $first ng-repeat item
var theHeight = el[0].offsetHeight;
// this fires the expMapper on parent directive.
ctrl.expMapper(offset, theHeight);
}
};
});

关于为什么不使用 watcher 的旁注:我不想使用观察者的原因是我将这些值推送到父指令中的集合。我不想继续重置数组,如果它在每个 2way 绑定(bind)上一直触发 ctrl.expMapper(),我就必须这样做。

父指令:

app.directive('scrollSpyer', function ($window, Experiences) {
return {
controller: function($scope){
$scope.experiences = [];
this.expMapper = function(offset, height) {
$scope.experiences.push({'offset': offset, 'height': height, 'inView': false});
};
},
link: function(scope) {
var i = 0;
angular.element($window).bind('scroll', function() {

if(i < scope.experiences.length) {
if (this.pageYOffset >= scope.experiences[i].offset) {
Experiences.status.push(scope.experiences[i]);
i++;
} else {
console.log('middle');
}
}

scope.$apply();
});
}
};
});

最佳答案

让它成为 $scope 中的一个函数:

$scope.getOffsets = function () {
//Do your logic here
};

注意这个小区别:

<dt  spyed ng-repeat="exp in experiences" ng-init="$last ? getOffsets(): ''">
...
</dt>

ng-init 基于条件来检查最后一个索引将使它在没有超时的情况下发生

关于javascript - 使用 ng-repeat 时如何获得元素的正确高度和偏移值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27596385/

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