繁体   English   中英

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

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

大家好,我对将来将要创建的元素具有绝对的立场。 我想检查元素是否在当前视口中完全可见。 我知道如果元素在页面上呈现,我可以使用getBoundingClientRect ,但是事实并非如此,也可能不是。 有没有一种方法可以检测给定的绝对坐标(左,上,下,右)在当前视口中是否可见? 提前致谢。

编辑:

到目前为止,我的解决方案是-插入具有visibility: hidden的元素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,width,height与视口的x,y,width,height之间的交集。

用户每次滚动时,只需点击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 );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM