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

use*_*582 19 jquery

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

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

有任何想法吗?我更喜欢使用jQuery.

Moh*_*sen 22

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

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

您可以通过计算element.offsetTop和计算元素与页面底部之间的间距window.innerHeight.

var space = window.innerHeight - element.offsetTop
Run Code Online (Sandbox Code Playgroud)

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

var space = window.innerHeight - element.offsetTop + element.offsetHeight
Run Code Online (Sandbox Code Playgroud)

有时需要这种计算.认为您有基于百分比的定位,并且您希望通过像素知道元素的位置以执行某些操作.例如,你有一个像这样的div:

div{
    width:300px;
    height:16.2%;
    position:absolute;
    top: 48.11%;
    border:3px dotted black;
}
Run Code Online (Sandbox Code Playgroud)

然后你想知道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';
    }
};
Run Code Online (Sandbox Code Playgroud)

小提琴

  • @CharlesRobertson 嗯,不,在添加/减去时不需要使用括号...... (3认同)
  • 我认为对于底部计算,这应该是 `- element.offsetHeight` 而不是 `+ element.offsetHeight` (2认同)

Sim*_*son 8

使用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');
};
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
<div class="outer">
  <div class="inner"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

如果您更喜欢使用jQuery,那么以下代码也可以使用:

var spaceBelow = $(window).height() - $('.inner')[0].getBoundingClientRect().bottom;
Run Code Online (Sandbox Code Playgroud)