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

如果一个元素是visiblehidden?


当前回答

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

其他回答

下面的代码检查元素是否隐藏在 jQuery 中或可见

// You can also do this...

        $("button").click(function(){
            // show hide paragraph on button click
            $("p").toggle("slow", function(){
                // check paragraph once toggle effect is completed
                if($("p").is(":visible")){
                    alert("The paragraph  is visible.");
                } else{
                    alert("The paragraph  is hidden.");
                }
            });
        });

如果隐藏在类 - d - no 类中

if (!$('#ele').hasClass('d-none')) {
        $('#ele').addClass('d-none'); //hide 

    }


  

只是简单地检查一下这个元素是否是可见可见然后,他将返回尘埃,布尔j 查询,通过添加来隐藏元素无显示无对于元素,所以如果您想要使用纯 JavaScript,您仍然可以这样做,例如:

if (document.getElementById("element").style.display === 'block') {
  // Your element is visible; do whatever you'd like
}

另外,您还可以使用 jQuery , 您的代码的其余部分似乎也使用 JQuery , 您的代码块较小 。 在 jQuery 中, 类似下面的密钥也可以使用相同的密钥 :

if ($(element).is(":visible")) {
    // Your element is visible, do whatever you'd like
};

还使用cssjQuery 中的方法可以产生相同的结果:

if ($(element).css('display') === 'block') {
    // Your element is visible, do whatever you'd like
}

若需要检查可见度和显示度,您还可以做以下工作:

if ($(this).css("display") === "block" || $(this).css("visibility") === "visible") {
   // Your element is visible, do whatever you'd like
}
if($("h1").is(":hidden")){
    // your code..
}

而不是撰写event每一单element,这样做:

$('div').each(function(){
  if($(this).css('display') === 'none'){
    $(this).css({'display':'block'});
  }
});

您也可以在以下输入中使用:

$('input').each(function(){
  if($(this).attr('type') === 'hidden'){
    $(this).attr('type', 'text');
  }
});