有一个由ng-repeat制作的列表,其中有很多行。
<ul ng-repeat="element in elements | filter:filterQuery">
<a class="row" >
<div class="col-lg-8">
<div class="caption">
<h4>{{element.artists[0].name}}</h4>
</div>
</div>
</a>
</ul>
我想找到哪个元素(垂直)位于屏幕的中心。
你可以帮帮我吗?我是Angular的新人。 我相信问题类似于无限滚动。但不是找到最后一个元素,而是需要在中心找到元素答案 0 :(得分:1)
这是一个可能的解决方案,我可能会自己解决这个问题:
scroll
事件侦听器。您也不应忘记维持正确的指令生命周期。这意味着删除事件侦听器和解除引用DOM节点以防止内存泄漏。
指令:
.directive("highlightCentermost", function ($window, $document, $timeout) {
return function postLink (scope, el) {
// References are kept here
var center, centermost
// Find and update centermost element
function probe () {
var newCentermost = $document[0].elementFromPoint(0, center)
// No centermost assigned yet
if (!centermost) {
centermost = newCentermost
centermost.classList.toggle("active", true)
return
}
// Found another element
if (centermost !== newCentermost) {
// Remove class from old element
centermost.classList.toggle("active", false)
// Add class to new element
newCentermost.classList.toggle("active", true)
// Update the reference
centermost = newCentermost
} else if (!newCentermost && centermost) {
// Cleanup if nothing was found
centermost.classList.toggle("active", false)
centermost = null
}
}
function resize () {
center = $window.innerHeight / 2
}
resize()
// $timeout is required to wait until all element directives are applied
$timeout(probe)
$window.addEventListener("scroll", probe)
$window.addEventListener("resize", resize)
scope.$on("$destroy", function cleanup () {
$window.removeEventListener("scroll", probe)
$window.removeEventListener("resize", resize)
centermost = null
})
}
})
优点:
缺点:
请注意,这是最基本的版本,您可能希望改进计算垂直中心和探测元素的函数(如探测两点而不是一点)。我在其中一个应用程序中使用了类似的方法来实现display:sticky
模拟,因此它非常灵活。
我可以提出更多解决方案:
scrollTop
值的元素当前条件。这是虚拟滚动背后的机制(仅显示视口中的项目,允许具有大量项目而不会影响性能)。答案 1 :(得分:0)
我不知道如何使用Angular 但要获得中间元素,你应该尝试类似的东西。
计算元素长度。 除以每两年的结果。
你的元素位于中心位置。 如果你有类似2.5的东西,可以在之前或之后定位到一个。
答案 2 :(得分:0)
嘿,我创造了小提琴http://jsfiddle.net/uwk46bky/1/ 可能有帮助: - )
<div ng-init="elements=['1','2','3','4','5']">
<ul ng-repeat="element in elements">
<a class="row" >
<div class="col-lg-8">
<div class="caption">
<h4 ng-class="{'check':($index+0.5)==(elements.length/2)}">{{element}}</h4>
</div>
</div>
</a>
</ul>
</div>
CSS: -
.check{
background-color:red;
}