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

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


当前回答

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

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

其他回答

if($(element).is(":visible")) {
  console.log('element is visible');
} else {
  console.log('element is not visible');
}

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

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

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

我只是想澄清一下, 在杰奎里,

元素可以被视作隐藏, 原因有几个: 它们有一个 css 显示值为零 。 它们是类型=“ 隐藏” 的形状元素。 它们的宽度和高度被明确设置为 0。 祖先元素被隐藏, 因此该元素不会在页面上显示 。 有可见度的元素: 隐藏或不透明: 0 被视为可见, 因为它们仍然在布局中消耗空间 。 在隐藏元素的动画中, 该元素被视为可见, 直到动画结束 。 sourc

if($('.element').is(':hidden')) {
  // Do something
}
isHidden = function(element){
    return (element.style.display === "none");
};

if(isHidden($("element")) == true){
    // Something
}

如何确定一个混合元素的状态?


您可以使用 : 可见和: 隐藏的选择器来确定元素是否崩溃。

var isVisible = $('#myDiv').is(':visible');
var isHidden = $('#myDiv').is(':hidden');

如果您只是根据一个基于其可见度的元素行事, 您可以只包括: 可见或: 隐藏在选择表达式中。 例如 :

 $('#myDiv:visible').animate({left: '+=200px'}, 'slow');