2011-10-05 267 views
11

我需要找到元素和浏览器窗口底部之间的距离。我需要找到元素和浏览器窗口底部之间的距离

当我选择元素,并且元素和浏览器窗口底部之间的距离小于50px时,我想让窗口自动滚动。

任何想法?我宁愿使用jQuery。

+0

所以,你要找到之间的距离*元素底部*和页面底部? – Ben

+0

是的!这就是我想要的:) – user979582

回答

17

与其他系统不同,浏览器中的坐标是从上到下的,这意味着浏览器的顶部是y = 0。

有两个DOM元素属性用于获取页面上元素的位置。属性是element.offsetTopelement.offsetHeight

您可以通过计算element.offsetTopwindow.innerHeight计算你的元素,并在页面底部之间的空间。

var space = window.innerHeight - element.offsetTop 

如果要计算元素底部和窗口底部之间的空间,则还需要添加元素高度。

var space = window.innerHeight - element.offsetTop + element.offsetHeight 

这种计算有时是必要的。认为你有基于百分比的定位,并且你想知道你的元素按像素位置来做什么。比如你有定位这样一个div:

div{ 
    width:300px; 
    height:16.2%; 
    position:absolute; 
    top: 48.11%; 
    border:3px dotted black; 
} 

那么你一定要知道什么时候该DIV接近浏览器窗口来改变它的颜色:

var div = document.querySelector('div'), 
    space = innerHeight - div.offsetTop + div.offsetHeight; 

window.onresize = function(){ 
    space = innerHeight - div.offsetTop + div.offsetHeight; 
    if(space < 200){ 
     div.style.background = 'blue'; 
    } 
}; 

Fiddle

+0

jquery?那不适用于铬我只是尝试了小提琴 – cppit

+0

@fogsy - 小提琴适用于我在Chrome使用版本35.0.1916.114 – DrewT

+0

@Mohsen括号请先生! var space = window.innerHeight - (element.offsetTop + element.offsetHeight);和一个jQuery等价物:var space = jQuery(window).height() - (element.offset()。top + element.outerHeight()); –

4

使用element.getBoundingClientRect()被一个很好的直接方法来获取相对于视口而不是文档的元素底部的偏移量。然后,您只需从window.innerHeight中减去此值即可计算元素与浏览器窗口底部(视口)之间的剩余空间。就像下面的例子:

var element = document.querySelector('.inner'); 
 

 
window.onscroll = function() { 
 
    var domRect = element.getBoundingClientRect(); 
 
    var spaceBelow = window.innerHeight - domRect.bottom; 
 
    
 
    element.style.background = (spaceBelow < 50 ? 'blue' : 'transparent'); 
 
};
body { 
 
    height: 1000px; 
 
} 
 

 
.outer { 
 
    position: absolute; 
 
    top: 120px; 
 
    border: 1px dashed green; 
 
    width: 95%; 
 
    height: 80px; 
 
} 
 

 
.inner { 
 
    width:300px; 
 
    height:16.2%; 
 
    position: absolute; 
 
    top: 48.11%; 
 
    border:3px dotted black; 
 
}
<div class="outer"> 
 
    <div class="inner"></div> 
 
</div>

如果你更喜欢使用jQuery,然后或者下面的代码也应该工作:

var spaceBelow = $(window).height() - $('.inner')[0].getBoundingClientRect().bottom; 
相关问题