如何使元素的可见度.hide(), .show(),或.toggle()?

如果一个元素是visiblehidden?


当前回答

因为Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout(截至2004年12月1日jj 查询: 可见选择器- 我们可以检查元素是否真的以这种方式可见:

function isElementReallyHidden (el) {
    return $(el).is(":hidden") || $(el).css("visibility") == "hidden" || $(el).css('opacity') == 0;
}

var booElementReallyShowed = !isElementReallyHidden(someEl);
$(someEl).parents().each(function () {
    if (isElementReallyHidden(this)) {
        booElementReallyShowed = false;
    }
});

其他回答

我会用CSS课.hide { display: none!important; }.

躲藏/展示,我打电话.addClass("hide")/.removeClass("hide")为了检查能见度,我使用.hasClass("hide").

这是一个简单清晰的检查/隐藏/显示元素的方法, 如果你不计划使用.toggle().animate()方法。

因为Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout(截至2004年12月1日jj 查询: 可见选择器- 我们可以检查元素是否真的以这种方式可见:

function isElementReallyHidden (el) {
    return $(el).is(":hidden") || $(el).css("visibility") == "hidden" || $(el).css('opacity') == 0;
}

var booElementReallyShowed = !isElementReallyHidden(someEl);
$(someEl).parents().each(function () {
    if (isElementReallyHidden(this)) {
        booElementReallyShowed = false;
    }
});

您可以使用hidden选择器 :

// Matches all elements that are hidden
$('element:hidden')

还有visible选择器 :

// Matches all elements that are visible
$('element:visible')

人们可以简单地使用hiddenvisible属性, 如 :

$('element:hidden')
$('element:visible')

或者您可以简化相同的如下所示。

$(element).is(":visible")

使用类切换,而不是样式编辑.

使用指定用于“隐藏”元素的分类很简单,也是最有效的方法之一。Display“ 无” 样式的“ 无” 样式的性能将比直接编辑该样式更快。 我在 Stack 溢出问题中非常透彻地解释了其中的一些内容 。在同一 div 中将两个元素转换为可见/隐藏.


JavaScript 最佳做法和优化

Google前端工程师Nicholas Zakas在Google Tech Talk的影片中,

  • 加快您的 Javastramp 速度(YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube)