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

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


当前回答

如果您想要检查页面上是否可见元素, 取决于其父的可见度, 您可以检查元素的宽度和高度是否均等于 0 。

jquery 圆

$ementle. width () 0

香草香草

元素. clishight = 0 元素. clishight 0

e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e. e.

其他回答

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

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

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($('#id_element').is(":visible")){
   alert('shown');
}else{
   alert('hidden');
}

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

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


缩略式最佳做法和优化

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

加速您的 Javascript (Youtube) 速度

因为元素具有可见度: 隐藏或不透明: 0 被视为可见, 因为它们仍然消耗着布局中的空间( 如 jquery 描述为 jquery : 可见选择器) - 我们可以检查元素是否以这种方式真正可见 :

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

a jquery 溶液, 但对于想更改按钮文字的人来说,

$( 函数 () { $( ” 显示) { $( 显示) { $( ” ) { var btn = $( 这样的) { btgle () { btn. text () { btn( $( ) ) {\\\ { display } } } }}} } () ) & lt; 上标 src=" https://ajax. googleapis. com/ jaax/ libs/jquery/ 2. 1 1/ jquery. min.js; & gt; / stamp&gt; = & lt; = "showhhide"; & gt; = " cont"; & h2 & gt; 某些内容 & h2 & gt; & lt; what is loremipsumsum? loremipsumpsum is 简单的文本。