我需要找到元素和瀏覽器窗口底部之間的距離。我需要找到元素和瀏覽器窗口底部之間的距離
當我選擇元素,並且元素和瀏覽器窗口底部之間的距離小於50px時,我想讓窗口自動滾動。
任何想法?我寧願使用jQuery。
我需要找到元素和瀏覽器窗口底部之間的距離。我需要找到元素和瀏覽器窗口底部之間的距離
當我選擇元素,並且元素和瀏覽器窗口底部之間的距離小於50px時,我想讓窗口自動滾動。
任何想法?我寧願使用jQuery。
與其他系統不同,瀏覽器中的座標是從上到下的,這意味着瀏覽器的頂部是y = 0。
有兩個DOM元素屬性用於獲取頁面上元素的位置。屬性是element.offsetTop
和element.offsetHeight
您可以通過計算element.offsetTop
和window.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';
}
};
使用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;
所以,你要找到之間的距離*元素底部*和頁面底部? – Ben
是的!這就是我想要的:) – user979582