如何使元素的可见度.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 解决方案, 但对于想更改按钮文字的人来说,

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

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

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

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

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

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

使用类切换,而不是样式编辑.

使用指定用于“隐藏”元素的分类很简单,也是最有效的方法之一。Display“ 无” 样式的“ 无” 样式的性能将比直接编辑该样式更快。 我在 Stack 溢出问题中非常透彻地解释了其中的一些内容 。在同一 div 中将两个元素转换为可见/隐藏.


JavaScript 最佳做法和优化

Google前端工程师Nicholas Zakas在Google Tech Talk的影片中,

  • 加快您的 Javastramp 速度(YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube)

因为Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout(截至2004年12月1日jj 查询: 可见选择器- 我们可以检查元素是否真的以这种方式可见:

function isElementReallyHidden (el) {
    return $(el).is(":hidden") || $(el).css("visibility") == "hidden" || $(el).css('opacity') == 0;
}

var booElementReallyShowed = !isElementReallyHidden(someEl);
$(someEl).parents().each(function () {
    if (isElementReallyHidden(this)) {
        booElementReallyShowed = false;
    }
});