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

如果一个元素是visiblehidden?


当前回答

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

 // 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($('#postcode_div').is(':visible')) {
    if($('#postcode_text').val()=='') {
        $('#spanPost').text('\u00a0');
    } else {
        $('#spanPost').text($('#postcode_text').val());
}
.is(":not(':hidden')") /*if shown*/

只需检查布林值, 即可检查可见度, 例如 :

if (this.hidden === false) {
    // Your code
}

我为每个函数使用此代码。 否则您可以使用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" });

有很多方法可以检查元素是否可见或隐藏在 jQuery 中。

Demo HTML 例如引用

<div id="content">Content</div>
<div id="content2" style="display:none">Content2</div>

使用可见性过滤过滤器选择器$('element:hidden')$('element:visible')

  • $('element:hidden'):选择隐藏的所有元素。

    Example:
       $('#content2:hidden').show();
    
  • $('element:visible'):选择可见的所有元素。

    Example:
       $('#content:visible').css('color', '#EEE');
    

更多信息http://api.jquery.com/category/selectors/visibility-filter-selectors/

使用使用is()过滤过滤

    Example:
       $('#content').is(":visible").css('color', '#EEE');

    Or checking condition
    if ($('#content').is(":visible")) {
         // Perform action
    }

更多信息http://api.jquery.com/is/