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

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


当前回答

if($('#id_element').is(":visible")){
   alert('shown');
}else{
   alert('hidden');
}

其他回答

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

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


缩略式最佳做法和优化

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

加速您的 Javascript (Youtube) 速度

我搜索了这个, 没有一个答案 是正确的我的情况, 所以我创造了一个功能, 返回假的,如果一个人的眼睛看不到元素

jQuery.fn.extend({
  isvisible: function() {
    //
    //  This function call this: $("div").isvisible()
    //  Return true if the element is visible
    //  Return false if the element is not visible for our eyes
    //
    if ( $(this).css('display') == 'none' ){
        console.log("this = " + "display:none");
        return false;
    }
    else if( $(this).css('visibility') == 'hidden' ){
        console.log("this = " + "visibility:hidden");   
        return false;
    }
    else if( $(this).css('opacity') == '0' ){
        console.log("this = " + "opacity:0");
        return false;
    }   
    else{
        console.log("this = " + "Is Visible");
        return true;
    }
  }  
});

而不是为每个元素写入事件, 请这样做 :

$('div').each(function(){
  if($(this).css('display') === 'none'){
    $(this).css({'display':'block'});
  }
});

您也可以在以下输入中使用:

$('input').each(function(){
  if($(this).attr('type') === 'hidden'){
    $(this).attr('type', 'text');
  }
});

有两种方法可以检查元素的可见度。

解决办法1

if($('.selector').is(':visible')){
    // element is visible
}else{
    // element is hidden
}

解决办法2

if($('.selector:visible')){
    // element is visible
}else{
    // element is hidden
}

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

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

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;
}