How do I check if an element is hidden in jQuery?

2018-12-31 01:51发布

It is possible to toggle the visibility of an element, using the functions .hide(), .show() or .toggle().

How would you test if an element is visible or hidden?

30条回答
有味是清欢
2楼-- · 2018-12-31 02:09

You can use the hidden selector:

// Matches all elements that are hidden
$('element:hidden')

And the visible selector:

// Matches all elements that are visible
$('element:visible')
查看更多
牵手、夕阳
3楼-- · 2018-12-31 02:10

This works for me, and I am using show() and hide() to make my div hidden/visible:

if( $(this).css('display') == 'none' ){
    /* your code goes here */
} else {
    /* alternate logic   */
}
查看更多
冷夜・残月
4楼-- · 2018-12-31 02:10

Example:

$(document).ready(function() {
  if ($("#checkme:hidden").length) {
    console.log('Hidden');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="checkme" class="product" style="display:none">
  <span class="itemlist"><!-- Shows Results for Fish --></span> Category:Fish
  <br>Product: Salmon Atlantic
  <br>Specie: Salmo salar
  <br>Form: Steaks
</div>

查看更多
无色无味的生活
5楼-- · 2018-12-31 02:10

Maybe you can do something like this

$(document).ready(function() {
   var visible = $('#tElement').is(':visible');

   if(visible) {
      alert("visible");
                    // Code
   }
   else
   {
      alert("hidden");
   }
});
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

<input type="text" id="tElement" style="display:block;">Firstname</input>

查看更多
残风、尘缘若梦
6楼-- · 2018-12-31 02:15

To check if it is not visible I use !:

if ( !$('#book').is(':visible')) {
    alert('#book is not visible')
}

Or the following is also the sam, saving the jQuery selector in a variable to have better performance when you need it multiple times:

var $book = $('#book')

if(!$book.is(':visible')) {
    alert('#book is not visible')
}
查看更多
还给你的自由
7楼-- · 2018-12-31 02:15

Also here's a ternary conditional expression to check the state of the element and then to toggle it:

$('someElement').on('click', function(){ $('elementToToggle').is(':visible') ? $('elementToToggle').hide('slow') : $('elementToToggle').show('slow'); });
查看更多
登录 后发表回答