如何通过javascript检查元素的可见性? [英] How to check element's visibility via javascript?

查看:84
本文介绍了如何通过javascript检查元素的可见性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我感兴趣的方式来检查一个元素是否有display:none style explicility(即style =display:none),有一个类具有(或继承)这种风格,隐藏(和我的元素继承此)



Case1:

  ; body>< div>< span style =display:none;>一些隐藏文字< / span>< / div> 

 < body>< div style =display:none;>< span>一些隐藏文字< / span>< / div& 

案例2:

 code> SomeClass {display:none; } 
< body>< div class =SomeClass>< span>一些隐藏文字< / span>< / div&感谢,

解决方案 / div>

您正在寻找两种不同方案的解决方案。



第一种方案是获取css属性的级联/计算风格。有关如何执行此操作,请参见此答案。 / p>

第二种情况是检测是否有任何元素的父级被隐藏。



您可以使用解决方案这里介绍(并且由jQuery / Sizzle使用,因为 1.3.2 ),只是读取元素的尺寸:

  var isVisible = element.offsetWidth> 0 || element.offsetHeight> 0; 

如果它有维度,那么它是可见的,因为它需要一些矩形空间)在文档中。请注意,此技术对于某些元素仍然有某些缺点某些浏览器,但在大多数情况下应该工作。


I'm interested in a way to check whether an element has display:none style explicility (ie style="display:none"), has a class that has (or inherits) this style, or one of its parents is hidden (and my element inherits this)

Case1:

<body><div><span style="display:none;">Some hidden text</span></div>

or

<body><div style="display:none;"><span>Some hidden text</span></div>

Case2:

SomeClass {   display:none;   }
<body><div class="SomeClass"><span>Some hidden text</span></div>

Thanks,

解决方案

You are looking for one solution to two different scenarios.

The first scenario is getting the cascaded/computed style for a css property. See this answer for how to do that.

The second scenario is detecting if any of an element's parents are hidden. This requires traversing and is cumbersome and slow.

You can take the solution outlined here (and employed by jQuery/Sizzle since 1.3.2), and just read the dimensions of the element:

var isVisible = element.offsetWidth > 0 || element.offsetHeight > 0;

If it has dimensions then it is visible in the sense that it takes up some rectangular space (however small) in the document. Note that this technique still has some downsides for certain elements in certain browsers, but should work in most cases.

这篇关于如何通过javascript检查元素的可见性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆