判断元素是否在屏幕中

ele.getBoundingClientRect()

此方法返回一个getClientRect集合,包含元素距离DOM可见视口top,left,bottom,right属性及widthheight属性。

这里写图片描述
注意这里的bottom指的是元素最下面距离视口顶部的距离。

判断页面是否出现滚动条

function isScrollY() {
    return document.documentElement.offsetHeight > document.documentElement.clientHeight;
}
function isScrollX() {
    return document.body.offsetWidth > document.documentElement.clientWidth;
}

获取滚动条的宽度

 function getScrollWidth () {
        var ele = document.createElement('div');
        ele.style.cssText = 'position:absolute;width:100px;height:100px;overflow:scroll;left:-1000px';
        document.body.appendChild(ele);
        var offsetWidth = ele.offsetWidth;
        var clientWidth = ele.clientWidth;
        var scrollWidth = offsetWidth-clientWidth;
        document.body.removeChild(ele);
        return scrollWidth;
    }

判断元素是否在屏幕中即能否看见

function eleUnvisible() {
        var ele = document.getElementsByClassName('div')[0];
        var getBoundingClientRect = ele.getBoundingClientRect();
         var scrollWidthX = isScrollX() ?  getScrollWidth() : 0;
        var scrollWidthY = isScrollY() ?  getScrollWidth() : 0;
        if (getBoundingClientRect.right < 1|| 
            getBoundingClientRect.bottom < 1) {
            return true;
        }
         if(getBoundingClientRect.left > (window.innerWidth - scrollWidthY) || getBoundingClientRect.top > (window.innerHeight - scrollWidthX)){
            return true;
        }
        return false;
    }
  • getBoundingClientRect.right<1则元素被隐藏在屏幕左边
  • getBoundingClientRect.bottom<1则元素被隐藏在屏幕上边
  • getBoundingClientRect.left > (window.innerWidth - scrollWidth)则元素被隐藏在屏幕右边
  • getBoundingClientRect.top > (window.innerHeight - scrollWidth)则元素被隐藏在屏幕下边
    这里用到window.innerHeight - scrollWidth来比较因为有滚动条的话若getBoundingClientRect.top被滚动条隐藏的话元素也是不可见的。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值