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

如果一个元素是visiblehidden?


当前回答

这里有一个永久有条件的表达式 来检查元素的状态 然后切换它:

$('someElement').on('click', function(){ $('elementToToggle').is(':visible') ? $('elementToToggle').hide('slow') : $('elementToToggle').show('slow'); });

其他回答

这个问题最简单的答案是:

function checkUIElementVisible(element) {
    return ((element.css('display') !== 'none') && (element.css('visibility') !== 'hidden'));
}

由于问题只涉及一个要素,本守则可能更适合:

// Checks CSS content for display:[none|block], ignores visibility:[true|false]
$(element).is(":visible");

// The same works with hidden
$(element).is(":hidden");

twernt的建议,但适用于单一个元素;并且匹配 jQuery FAQ 中推荐的算法.

我们用jQuery的是( )将选中的元素与其它元素、选择器或任何 jQuery 对象一起检查。此方法沿 DOM 元素沿 DOM 元素查找匹配,该匹配符合所传递的参数。如果匹配,则返回为真实,否则返回为虚假。

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>

您可以使用hidden选择器 :

// Matches all elements that are hidden
$('element:hidden')

还有visible选择器 :

// Matches all elements that are visible
$('element:visible')

您可以使用这个:

$(element).is(':visible');

示例代码

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

    $("#visiblity").click(function()
    {
       if( $('#content').is(':visible') )
       {
          alert("visible"); // Put your code for visibility
       }
       else
       {
          alert("hidden");
       }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

<p id="content">This is a Content</p>

<button id="toggle">Toggle Content Visibility</button>
<button id="visibility">Check Visibility</button>