判断Element是否隐藏

判断一个元素是否隐藏,可以先思考怎么隐藏一个元素呢?
display:none; visibility:hidden;
通过设置position:absolutely,top,left设置为负值 margin设置为负值

最近在看Angular 0.10.0 版本的源码
注释也是相当的pretty。

其中涉及到判断Element元素是否可视的方法isVisible

源码是这样的

function isVisible(element) {
        var rect = element[0].getBoundingClientRect(),
            width = (rect.width || (rect.right||0 - rect.left||0)),
            height = (rect.height || (rect.bottom||0 - rect.top||0));
        return width>0 && height>0;
    }

其中主要用到了ele.getBoundingClientRect()
利用这个方法可以获取元素的size以及元素各个边距离页面原点的距离。

MDN的官网解释是:
The Element.getBoundingClientRect() method returns the size of an element and its position relative to the viewport.

兼容问题
[1]In IE8 and below, the DOMRect object returned by getBoundingClientRect() lacks height and width properties.

Angular 0.10.0 源码中的代码就是考虑到了兼容性写的

 width = (rect.width || (rect.right||0 - rect.left||0)),
 height = (rect.height || (rect.bottom||0 - rect.top||0));

释后,为了真正的理解需要进一步实践这个方法

代码是在 Google Chrome 版本 56.0.2924.87 (64-bit)
console中输出的结果

实践1

 <div style="width: 100px; height: 100px; background-color: red"></div>
   var ele = document.querySelector('div');
   var rect = ele.getBoundingClientRect();
   //{ top: 8, right: 108, bottom: 108,  left: 8, width: 100, height: 100}

实践2 div 设置为 display: none

 <div style="width: 100px; height: 100px; background-color: red;display: none"></div>
   var ele = document.querySelector('div');
   var rect = ele.getBoundingClietRect();
   //{ top: 0, right: 0, bottom: 0,  left: 0, width: 0, height: 0}

实践3 div 设置为 visibility: hidden

 <div style="width: 100px; height: 100px; background-color: red;visibility: hidden"></div>
   var ele = document.querySelector('div');
   var rect = ele.getBoundingClietRect();
   //{ top: 8, right: 108, bottom: 108,  left: 8, width: 100, height: 100}

实践3 div 设置为 position: absolutely; top: -200px; left: -200px

 <div style="width: 100px; height: 100px; background-color: red;position: absolutely; top: -200px; left: -200px"></div>
   var ele = document.querySelector('div');
   var rect = ele.getBoundingClietRect();
   //{ top: -200, right: -200, bottom: -100,  left: -100, width: 100, height: 100}

这说明了Element.getBoundingClientRect() 会引发回流,检查元素的是否为display: none

领个红包,小赞赏一下吧

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值