我需要知道是否有办法确定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。
由于
答案 0 :(得分:7)
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);
另一种方法(仅适用于现代浏览器)是使用intersection API
答案 1 :(得分:2)
窗口的高度和窗口的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;
}
});
没有对此进行测试,但它应该沿着正确的轨道进行测试。
答案 2 :(得分:1)
这是一个很好的方法:elementFromPoint()
您可以在中心获取元素:
var elem = document.elementFromPoint($(window).width()/2, $(window).height()/2);
//if you want jquery element you can get it.
var jqueryElem = $(elem);