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

如果一个元素是visiblehidden?


当前回答

而不是撰写event每一单element,这样做:

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

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

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

其他回答

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

它返回时返回false如果元素不可见。

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

只需检查布林值, 即可检查可见度, 例如 :

if (this.hidden === false) {
    // Your code
}

我为每个函数使用此代码。 否则您可以使用is(':visible')检查某一要素的可见度。

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

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

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


JavaScript 最佳做法和优化

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

  • 加快您的 Javastramp 速度(YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube)
if ( $(element).css('display') == 'none' || $(element).css("visibility") == "hidden"){
    // 'element' is hidden
}

上述方法不考虑父母亲的可见度。为了也考虑父母的可见度,您应该使用.is(":hidden").is(":visible").

例如,

<div id="div1" style="display:none">
  <div id="div2" style="display:block">Div2</div>
</div>

上述方法将考虑div2可见时可见:visible。但是,在很多情况下,特别是当您需要找到隐藏的父(母)是否发现任何错误时,上述情况也许有用,因为在这种情况下,隐藏的母(母)之间是否有错误。:visible不会工作。