如何使用 . hide () 、.show () 或.toggle () 来切换元素的可见度 ?

如果元素可见或隐藏, 我如何测试 ?


当前回答

但如果元素的 css 和下面一样呢?

.element{
    position: absolute;left:-9999;    
}

因此,对于堆叠溢出问题的答案是,如何检查元素是否在屏幕之外,也应当考虑。

其他回答

您需要检查... 显示和可见度 :

if ($(this).css("display") == "none" || $(this).css("visibility") == "hidden") {
    // The element is not visible
} else {
    // The element is visible
}

如果我们自动检查$( thiss) 。 is (“: 可见”) , jquery check for both the things 自动检查 。

用于检查元素是否可见、不显示,甚至不透明度水平的扩展功能

如果元素不可见, 它返回错误 。

function checkVisible(e) {
    if (!(e instanceof Element)) throw Error('not an Element');
    const elementStyle = getComputedStyle(e);
    if (elementStyle.display === 'none' || elementStyle.visibility !== 'visible' || elementStyle.opacity < 0.1) return false;
    if (e.offsetWidth + e.offsetHeight + e.getBoundingClientRect().height +
        e.getBoundingClientRect().width === 0) {
        return false;
    }
    const elemCenter   = {
        x: e.getBoundingClientRect().left + e.offsetWidth / 2,
        y: e.getBoundingClientRect().top + e.offsetHeight / 2
    };
    if (elemCenter.x < 0 || elemCenter.y < 0) return false;
    if (elemCenter.x > (document.documentElement.clientWidth || window.innerWidth)) return false;
    if (elemCenter.y > (document.documentElement.clientHeight || window.innerHeight)) return false;
    let pointContainer = document.elementFromPoint(elemCenter.x, elemCenter.y);
    do {
        if (pointContainer === e) return true;
    } while (pointContainer = pointContainer.parentNode);
    return false;
}

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

使用指定用于“ 隐藏” 元素的类是容易的, 也是最有效的方法之一 。 套用“ 隐藏” 的显示样式“ 无” 将比直接编辑该样式更快 。 我在堆叠溢出问题中解释了其中的一些内容, 使两个元素可见/ 隐藏在同一 div 中 。


缩略式最佳做法和优化

Google前端工程师Nicholas zakas在Google科技演讲中,

加速您的 Javascript (Youtube) 速度

:根据 jquery 文档显示的可见选择器:

它们有一个 cs 显示无值。 它们是类型 = “ 隐藏” 的形状元素。 它们宽度和高度被明确设置为 0。 祖先元素被隐藏, 因此该元素不会在页面上显示 。 具有可见度的元素: 隐藏或不透明: 0 被视为可见, 因为它们仍然在布局中消耗空间 。

在某些情况中这是有用的,在另一些情况中是没用的,因为如果你想检查元素是否可见(播放=无),忽略父母的可见度,你会发现做.css(“播放”) =“无”不仅速度更快,而且还会正确返回可见度检查。

如果您想要检查可见度而不是显示, 您应该使用: . css (“ 可见度 ” ) = “ 隐藏 ” 。

还考虑到以下补充简记:

因为 : 可见的扩展是一个缩略语, 而不是 cs 规格的一部分, 使用 : 可见 无法利用本地的 dom 查询 Electultl () 方法提供的性能增强 。 使用 : 可见 来选择元素, 首先使用纯 cs 选择器选择元素, 然后使用 . fileter (“ 可见 ” : 可见 ) 来达到最佳性能 。

另外,如果你担心性能,你应该检查一下现在你看到我... 表现/隐藏性能(2010-05-04),并使用其他方法来显示和隐藏元素。

您可以使用此功能:

$(element).is(':visible');

示例代码

$( document) {( pready) {( ) {( ) {( ) $( ” tggle” ) . click () {( ) {( ) {( ) {( ) {( ) {( ) $( ) ) {( ) $( ) ) } . 点击 ( ) {( ) {( ) {( ” ) } } } } ; & ; 标注 src=" https://ajaax.googleapis.com/ax/libs/ jquery/ 12.2/ query. min. js&gt; & () / statict&gt; & pl= "content" & gt; this is a