如何使元素的可见度.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  
   // };  

其他回答

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

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

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

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

有两种方法可以检查元素的可见度。

解决方案 # 1

if($('.selector').is(':visible')){
    // element is visible
}else{
    // element is hidden
}

解决方案 # 2

if($('.selector:visible')){
    // element is visible
}else{
    // element is hidden
}
$('someElement').on('click', function(){ $('elementToToggle').is(':visible')

您可以在显示或隐藏 CSS 类时使用该类的 CSS 类 :

.show{ display :block; }

设置您的j查询toggleClass()addClass()removeClass();.

例如,

jQuery('#myID').toggleClass('show')

上述代码将添加show当元素没有 cs 元素时 cs 类show当它消逝的时候,show类。

当你在检查它是否可见, 你可以遵循这个 JQuery 代码,

jQuery('#myID').hasClass('show');

上面的代码将返回布尔值( true) 时返回布尔值#myID元素中含有我们的类(show当它没有的时候,是假的,show类。

jQuery 解决方案, 但对于想更改按钮文字的人来说,

$(function(){
  $("#showHide").click(function(){
    var btn = $(this);
    $("#content").toggle(function () {
      btn.text($(this).css("display") === 'none' ? "Show" : "Hide");
    });
   });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="showHide">Hide</button>
<div id="content">
  <h2>Some content</h2>
  <p>
  What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
  </p>
</div>