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

如果一个元素是visiblehidden?


当前回答

这个问题最简单的答案是:

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

其他回答

这对我有效,我用show()hide()使我的divi 隐藏/可见:

if( $(this).css('display') == 'none' ){
    /* your code goes here */
} else {
    /* alternate logic   */
}

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 查看元素是否隐藏或可见 ?

使用任何可见的选择器或隐藏的选择器检查粘度 :

  1. 使用使用: 可见选择器 - jQuery (“ : 可见” )
  2. 使用: hidden 选择器 - jQuery (“ : hidden ” )

使用.toggle ()- 显示和隐藏元素

function checkVisibility() {
    // check if element is hidden or not and return true false
    console.log($('#element').is(':hidden'));

    // check if element is visible or not and return true false
    console.log($('#element').is(':visible'));

    if ( $('#element').css('display') == 'none' || $('#element').css("visibility") == "hidden"){
        console.log('element is hidden');
    } else {
        console.log('element is visibile');
    }
}

checkVisibility()
$('#toggle').click(function() {
    $('#element').toggle()
    checkVisibility()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='toggle'>Toggle</button>
<div style='display:none' id='element'>
    <h1>Hello</h1>
    <p>it's visible</p>
</div>

expect($("#message_div").css("display")).toBe("none");

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

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

如果有的话它返回为真show类。

添加像这样的 CSS :

.show{ display: block; }