![](/img/trans.png)
[英]Find element that's on the middle of the visible screen (viewport) to target another element
[英]Find element that's on the middle of the visible screen (viewport), on scroll
我需要知道是否有一种方法可以确定div是否在屏幕的中心。
<div id="container">
<div class="box" id="box0">
text
</div>
<div class="box" id="box1">
text
</div>
.....
<div class="box" id="box100">
text
</div>
</div>
考虑到页面是可滚动的,有没有办法确定div何时位于可见屏幕的中心? 所以基本上,当用户向下滚动页面时,应该选择位于可见屏幕中间的div。
谢谢
var findMiddleElement = (function(docElm){
var viewportHeight = docElm.clientHeight,
// here i'm using pre-cached DIV elements, but you can use anything you want.
// Cases where elements are generated dynamically are more CPU intense ofc.
elements = $('div');
return function(e){
var middleElement;
if( e && e.type == 'resize' )
viewportHeight = docElm.clientHeight;
elements.each(function(){
var pos = this.getBoundingClientRect().top;
// if an element is more or less in the middle of the viewport
if( pos > viewportHeight/2.5 && pos < viewportHeight/1.5 ){
middleElement = this;
return false; // stop iteration
}
});
console.log(middleElement);
}
})(document.documentElement);
$(window).on('scroll resize', findMiddleElement);
另一种方法(仅适用于现代浏览器)是使用交集API
窗口的高度和窗口的scrollTop()将为您提供用户视图中存在的偏移范围:
var minHeight = $(window).scrollTop()
var maxHeight = $(window).height()
var middleHeight = (maxHeight + minHeight) / 2;
您可以尝试使用视口选择器,例如: http : //www.appelsiini.net/projects/viewport这将为您提供所有可见元素。 不需要插件,但可以简化选择
var visibleElements = $("div.box").filter(":in-viewport")
从这个选择中,您可以查找最接近middleHeight的元素:
var $midElement;
var distance = null;
var currDistance = 0;
visibleElements.each(function(index, element) {
currDistance = Math.abs(middleHeight - $midElement.offset().top);
if ( distance == null || currDistance < distance ) {
$midElement = $(element);
distance = currDistance;
}
});
没有测试过这个,但它应该是正确的轨道。
这是一个不错的方法: elementFromPoint()
您可以将元素放在中心,如下所示:
var elem = document.elementFromPoint($(window).width()/2, $(window).height()/2);
//if you want jquery element you can get it.
var jqueryElem = $(elem);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.