Javascript Tool: Detect if a DOM Element is Truly Visible

来源:互联网 发布:淘宝 评价数 销量 编辑:程序博客网 时间:2024/05/20 12:50

one way:

According to this MDN documentation, an element's offsetParent property will return null whenever it, or any of its parents, is hidden via the display style property. Just make sure that the element isn't fixed. A script to check this, if you have no 'position:fixed;' elements on your page, might look like:

//Where el is the DOM element you'd like to test for visibilityfunction isHidden(el) {    if (el.offsetParent === null) {        return true;    }    return false;}

On the other hand, if you do have position fixed elements that might get caught in this search, you will sadly (and slowly) have to use window.getComputedStyle(). The function in that case might be:

//Where el is the DOM element you'd like to test for visibilityfunction isHidden(el) {    var style = window.getComputedStyle(el);    if (style.display === 'none') {        return true;    }    return false;}

Option #2 is probably a little more straightforward since it accounts for more edge cases, but I bet its a good deal slower, too, so if you have to repeat this operation many times, best to probably avoid it.

another way:

点击打开链接

0 0
原创粉丝点击