我需要知道是否有一种方法可以确定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>
Run Code Online (Sandbox Code Playgroud)
考虑到页面是可滚动的,有没有办法确定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);
Run Code Online (Sandbox Code Playgroud)
另一种方法(仅适用于现代浏览器)是使用交集API
这是一个很好的方法:elementFromPoint()
您可以将元素置于中心,如下所示:
var elem = document.elementFromPoint($(window).width()/2, $(window).height()/2);
//if you want jquery element you can get it.
var jqueryElem = $(elem);
Run Code Online (Sandbox Code Playgroud)
窗口的高度和窗口的scrollTop()将为您提供用户视图中存在的偏移范围:
var minHeight = $(window).scrollTop()
var maxHeight = $(window).height()
var middleHeight = (maxHeight + minHeight) / 2;
Run Code Online (Sandbox Code Playgroud)
您可以尝试使用视口选择器,例如: http://www.appelsiini.net/projects/viewport 这将为您提供所有可见元素。不需要插件,但可以简化选择
var visibleElements = $("div.box").filter(":in-viewport")
Run Code Online (Sandbox Code Playgroud)
然后,您可以从该选择中查找最接近 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;
}
});
Run Code Online (Sandbox Code Playgroud)
还没有测试过,但它应该是沿着正确的轨道。
| 归档时间: |
|
| 查看次数: |
8237 次 |
| 最近记录: |