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

如果一个元素是visiblehidden?


当前回答

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

解决方案 # 1

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

解决方案 # 2

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

其他回答

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();
    });    
});
if($('#postcode_div').is(':visible')) {
    if($('#postcode_text').val()=='') {
        $('#spanPost').text('\u00a0');
    } else {
        $('#spanPost').text($('#postcode_text').val());
}

通常当检查某物是否可见时, 您会立即直接去做其他事情。 jQuery 链条让事情变得容易。

所以,如果您有一个选择器, 并且只有显示或隐藏时才想要对它执行某些动作, 您可以使用filter(":visible")filter(":hidden")然后用您想要采取的行动链绑住它。

所以,而不是一个if语句, 像这样的语句 :

if ($('#btnUpdate').is(":visible"))
{
     $('#btnUpdate').animate({ width: "toggle" });   // Hide button
}

或更有效率,但更丑陋:

var button = $('#btnUpdate');
if (button.is(":visible"))
{
     button.animate({ width: "toggle" });   // Hide button
}

你可以单行完成所有任务:

$('#btnUpdate').filter(":visible").animate({ width: "toggle" });

您需要同时检查 显示和可见度 :

if ($(this).css("display") == "none" || $(this).css("visibility") == "hidden") {
    // The element is not visible
} else {
    // The element is visible
}

如果我们检查$(this).is(":visible"),j 查询自动检查这两个东西。