【问题标题】:Change visibility of another element if display none in jQuery如果在 jQuery 中不显示,则更改另一个元素的可见性
【发布时间】:2018-03-23 13:00:15
【问题描述】:

如果特定元素有display:none,我需要更改另一个元素的显示属性。

if ($("#first-layer").css('display') === 'none') {
  $("#second-layer").removeAttr("visibility");
}
#second-layer {
  color: black;
  background-color: red;
  width: 200px;
  height: 150px;
  background: yellow;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  visibility: hidden; // here I have to change by jQuery
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<header>
  <div id="first-layer">
    <div id="header-elements">
      <div id="img-rain" class="animated fadeIn" class="img"><img src="img/img.png"> </div>
      <div id="typed-strings" class="text">
        <span class="animated fadeInUp" id="typed"></span>
        <br/>
        <span class="description animated fadeIn">Your weather in one place</span>
      </div>
    </div>
    <div id="typed-strings">
    </div>
    <div class="start">
      <button type="button" class="btn btn-primary btn-lg responsive-width button-                       bg-clr animated fadeIn">Get Started</button>
    </div>
  </div>
  <div id="second-layer">123</div>

</header>

我尝试了互联网上的解决方案,但没有奏效。

【问题讨论】:

  • 可见性:隐藏;不是属性,因此您不能使用 removeAttr 定位它

标签: jquery html css hidden display


【解决方案1】:

使用jQuery( ":hidden" )

// if selector is none then
if($('#first-layer').is(":hidden")){

     // alter second-layers visibility
     $('#second-layer').css('visibility', 'visible');
}

【讨论】:

    【解决方案2】:

    您的代码目前没有做任何事情,但您可能会更轻松地使用

    if ($("#first-layer").not(":visible")) { // or .is(":hidden")
      $("#second-layer").show();
    }
    

    $("#second-layer").css({visibility:visible});
    

    因为 CSS 声明不是属性

    在此处了解有关检测的更多信息 Difference between :hidden and :not(:visible) in jQuery

    【讨论】:

    • 非常感谢:) 结果:我在css中设置了第二层显示:无,在JS中我放了这个:if ($("#first-layer").is(":隐藏")) { $("#second-layer").css('display', 'block'); }
    猜你喜欢
    • 2016-11-03
    • 2017-06-24
    • 1970-01-01
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    相关资源
    最近更新 更多