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

如果一个元素是visiblehidden?


当前回答

但如果元素的 CSS 和下面一样呢?

.element{
    position: absolute;left:-9999;    
}

Stack 溢出问题的此答案如何检查元素是否在屏幕外还应加以考虑。

其他回答

使用隐藏选择, 您可以匹配所有隐藏元素

$('element:hidden')

使用可见选择, 您可以匹配所有可见元素

$('element:visible')

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>

   hideShow(){
  $("#accordionZiarat").hide();
  // Checks CSS content for display:[none|block], ignores visibility:[true|false]
  if ($("#accordionZiarat").is(":visible")) {
    $("#accordionZiarat").hide();
  }

  
  else if ($("#accordionZiarat").is(":hidden")) {
    $("#accordionZiarat").show();
  }

  else{

  }
isHidden = function(element){
    return (element.style.display === "none");
};

if(isHidden($("element")) == true){
    // Something
}

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