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

如果一个元素是visiblehidden?


当前回答

人们可以简单地使用hiddenvisible属性, 如 :

$('element:hidden')
$('element:visible')

或者您可以简化相同的如下所示。

$(element).is(":visible")

其他回答

通常当检查某物是否可见时, 您会立即直接去做其他事情。 jQuery 链条让事情变得容易。

所以,如果您有一个选择器, 并且只有显示或隐藏时才想要对它执行某些动作, 您可以使用filter(":visible")filter(":hidden")然后用您想要采取的行动链绑住它。

所以,而不是一个if语句, 像这样的语句 :

if ($('#btnUpdate').is(":visible"))
{
     $('#btnUpdate').animate({ width: "toggle" });   // Hide button
}

或更有效率,但更丑陋:

var button = $('#btnUpdate');
if (button.is(":visible"))
{
     button.animate({ width: "toggle" });   // Hide button
}

你可以单行完成所有任务:

$('#btnUpdate').filter(":visible").animate({ width: "toggle" });
expect($("#message_div").css("display")).toBe("none");
.is(":not(':hidden')") /*if shown*/

此选项可以检查标签是否可见

 // using a pure CSS selector  
   if ($('p:visible')) {  
      alert('Paragraphs are visible (checked using a CSS selector) !');  
   };  
  
   // using jQuery's is() method  
   if ($('p').is(':visible')) {  
      alert('Paragraphs are visible (checked using is() method)!');  
   };  
  
   // using jQuery's filter() method  
   if ($('p').filter(':visible')) {  
      alert('Paragraphs are visible (checked using filter() method)!');  
   };  
  
   // you can use :hidden instead of :visible to reverse the logic and check if an element is hidden  
   // if ($('p:hidden')) {  
   //    do something  
   // };  

要检查它是否不可见, 我使用它!:

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

或以下是 sam, 将 jQuery 选择器保存在一个变量中, 以便在您需要它多次时有更好的性能 :

var $book = $('#book')

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