判断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

领个红包,小赞赏一下吧

你可能感兴趣的:(JavaScript)