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

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


当前回答

您可以在可见时添加一个类。添加一个类,显示。然后检查是否有一个类:

$('#elementId').hasClass('show');

如果您有表演类, 它返回为真 。

添加这样的 cs :

.show{ display: block; }

其他回答

ebdiv 应设置为样式=“ display: noone; ” 。 它用于显示和隐藏 :

$(document).ready(function(){
    $("#eb").click(function(){
        $("#ebdiv").toggle();
    });    
});

由于问题只涉及一个要素,本守则可能更适合:

// Checks CSS content for display:[none|block], ignores visibility:[true|false]
$(element).is(":visible");

// The same works with hidden
$(element).is(":hidden");

它与twern的建议相同,但适用于一个单一要素;它与jquery faq中推荐的算法相符。

我们用 jquery's is () 来检查选中元素与其它元素、 选择器或任何 jquery 对象的对比。 此方法沿 dom 元素绕行查找匹配, 满足已传递参数 。 如果匹配, 返回为真, 否则返回为假 。

只需通过检查布林值来检查可见性, 例如 :

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

i 为每个函数使用此代码。 否则您可以使用( “: 可见” ) 来检查元素的可见度 。

$( "div:visible" ).click(function() {
  $( this ).css( "background", "yellow" );
});
$( "button" ).click(function() {
  $( "div:hidden" ).show( "fast" );
});

api 文档: 可见选择器

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

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

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