有几种方法可以做到这一点(据我所知)。
测试css显示
if ($('#foo').css('display') == 'none')
测试可见性
if ($('#foo').is(':visible'))
在可见性中我可以检查元素是否存在。
Elements are considered visible if they consume space in the document. Visible elements have a width or height that is greater than zero.
Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout.
但是,请注意,在两者中我都无法测试可见性(由用户),因为:
Hiding an element can be done by setting the display property to "none" or the visibility property to "hidden". However, notice that these two methods produce different results:
visibility: hidden hides an element, but it will still take up the same space as before. The element will be hidden, but still affect the layout.
display: none hides an element, and it will not take up any space. The element will be hidden, and the page will be displayed as if the element is not there:
因此,在这两个示例中,我都没有测试元素是否在所有意义上对用户可见。
所以我的问题是:
- 上面的两个 if 代码有什么区别?
- 测试元素是否对用户可见的最佳方法是什么:
我是否必须使用类似的东西:
if ($('#foo').is(':visible') &&
$('#foo').css('opacity') > 0 &&
$('#foo').css('visibility') != 'hidden')
最佳答案
我认为你最好的选择是实现如下所示的自定义函数,并在出现新事物时进行测试/改进,
$.fn.isReallyVisible = function () { //rename function name as you like..
return (this.css('display') != 'none' &&
this.css('visibility') != 'hidden' &&
this.css('opacity') > 0);
}
上面应该是跨浏览器证明,因为我们正在使用 jQuery .css
函数(专门用于不透明度)。
关于javascript - 测试 DOM 中元素的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10589810/