JavaScript - 检查绝对坐标(左、上、右、下)是否在当前视口上可见

JavaScript - Check if absolute coordinates (left, top, right, bottom) are going to be visible on the current viewport

本文关键字:是否 视口 坐标 JavaScript 检查      更新时间:2023-09-26

嘿伙计们,我对将来将要创建的元素有一个绝对的位置。我想检查该元素是否在当前视口上完全可见。我知道如果元素呈现在页面上,我可以使用 getBoundingClientRect,但它不是,也不可能不是。有没有办法检测给定的绝对坐标(左、上、下、右)是否在当前视口上可见?提前谢谢。

编辑:

到目前为止,我的解决方案 - 插入一个带有visibility: hidden的元素并使用getBoundingClientRect,我只是想知道是否有更好的方法。

如果你有这个未渲染元素的绝对坐标(即:你可以从JS变量中提取它们,或者从某个地方读取它们,或者对它们进行硬编码,甚至编写一个脚本从页面上的<style>标签中读取它们......),那么你可以做这样的事情:

var viewport = {
    x : 0,
    y : 0,
    width : 0,
    height : 0,
    update : function () {
        this.x = document.body.scrollLeft || document.documentElement.scrollLeft;
        this.y = document.body.scrollTop  || document.documentElement.scrollTop;
        this.width  = document.documentElement.clientWidth;
        this.height = document.documentElement.clientHeight;
    }
};
现在,您应该能够检查元素的x,y,宽度,高度

与视口的x,y,宽度,高度之间的交集。

每当用户滚动时,只需点击viewport.update();即可。

我会这样说:

这种方法应该相当跨浏览器兼容,但我真的不能在IE6方面做出任何保证 - 特别是在Quirksmode中(html文件没有<!doctype>)。

检查 screen.height 和 screen.width 并将其与元素的尺寸进行比较

看看这个: https://stackoverflow.com/a/1823700/1060487

function alertSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  window.alert( 'Width = ' + myWidth );
  window.alert( 'Height = ' + myHeight );
}