javascript - 测试 DOM 中元素的最佳方法是什么

标签 javascript jquery css performance dom

有几种方法可以做到这一点(据我所知)。

测试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.

Source

但是,请注意,在两者中我都无法测试可见性(由用户),因为:

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:

Source

因此,在这两个示例中,我都没有测试元素是否在所有意义上对用户可见。

所以我的问题是:

  • 上面的两个 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 函数(专门用于不透明度)。

DEMO

关于javascript - 测试 DOM 中元素的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10589810/

相关文章:

javascript - trim 第一个字母之后的所有字母

jQuery 删除复选框和关联标签

javascript - 在 Android+PhoneGap 中添加关于滚动的帖子

html - 垂直对齐 Bootstrap 样式标签和链接中的文本

javascript - 根本不显示 ionic View

javascript - 使用 Polymer 路由事件

jquery - 无法将 JSON 发送到服务器

jquery - 无法将自定义光标添加到可排序(jQuery、CSS)

javascript - 使用或不使用 flexbox 填充可用空间

javascript - 将 jQuery 覆盖功能指定给一个元素,而不是一次打开所有元素