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

如果一个元素是visiblehidden?


当前回答

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

  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>

其他回答

if($('#id_element').is(":visible")){
   alert('shown');
}else{
   alert('hidden');
}

有很多方法可以检查元素是否可见或隐藏在 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/

if($("h1").is(":hidden")){
    // your code..
}

$(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>

ebdiv定 定 定style="display:none;"它既用于显示也用于隐藏:

$(document).ready(function(){
    $("#eb").click(function(){
        $("#ebdiv").toggle();
    });    
});