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

如果一个元素是visiblehidden?


当前回答

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

它返回时返回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;
}

其他回答

isHidden = function(element){
    return (element.style.display === "none");
};

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

Demo 链接

$('#clickme').click(function() {
  $('#book').toggle('slow', function() {
    // Animation complete.
    alert($('#book').is(":visible")); //<--- TRUE if Visible False if Hidden
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clickme">
  Click here
</div>
<img id="book" src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png" alt="" width="300"/>

来源(来自我的博客):

博客 Plug n Play - jQuery 工具及部件: 如何使用 jQuery 查看元素是否隐藏或可见 ?

可以创建一个函数来检查可见度/显示属性,以便测量该元素是否显示在界面中。

function checkUIElementVisible(element) {
    return ((element.css('display') !== 'none') && (element.css('visibility') !== 'hidden'));
}

中小工作

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

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

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

twernt的建议,但适用于单一个元素;并且匹配 jQuery FAQ 中推荐的算法.

我们用jQuery的是( )将选中的元素与其它元素、选择器或任何 jQuery 对象一起检查。此方法沿 DOM 元素沿 DOM 元素查找匹配,该匹配符合所传递的参数。如果匹配,则返回为真实,否则返回为虚假。

您需要同时检查 显示和可见度 :

if ($(this).css("display") == "none" || $(this).css("visibility") == "hidden") {
    // The element is not visible
} else {
    // The element is visible
}

如果我们检查$(this).is(":visible"),j 查询自动检查这两个东西。