动画一个绝对定位儿童溢出的容器

时间:2018-01-15 20:53:15

标签: javascript jquery html css

我正在滑动100%宽度和100%高度的容器,而另一个容器从屏幕上移动以进行导航,但是每​​当动画开始时我的绝对定位项目都会变得可见。 this问题的第一个答案是说有一行代码会溢出,隐藏,但似乎无法正常工作。

$(document).ready(function(){
  var hash = location.hash;
  console.log(hash);
  $(window).on("hashchange",function(){
    hash=hash?hash:"#page1";
    $(hash)
    //I have tried adding
    //.css("overflow","hidden");
    .animate({height:"hide"});
    hash = location.hash
    $(hash)
    //I have tried adding
    //.css("overflow","hidden");
    .animate({height:"show"});
  });
  hash?$(hash).toggleClass("page-active"):$("#page1").toggleClass("page-active");
});

此处为jsfiddle

1 个答案:

答案 0 :(得分:1)

这是因为您使用固定位置作为锚点,因此它们相对于浏览器定位。而是使用position:absolute并使其父position:relative成为相对于其容器的位置,并使其容器顺利显示

$(document).ready(function() {
  var hash = location.hash;
  $(window).on("hashchange", function() {
    hash = hash ? hash : "#page1";
    $(hash)
      //I have tried adding
      //.css("overflow","hidden");
      .animate({
        height: "hide"
      });
    hash = location.hash
    $(hash)
      //I have tried adding
      //.css("overflow","hidden");
      .animate({
        height: "show"
      });
  });
  hash ? $(hash).toggleClass("page-active") : $("#page1").toggleClass("page-active");
});
body,
html {
  width: 100%;
  height: 100%;
  text-align: center;
  margin:0;
}

.page1 {
  width: 100%;
  height: 100%;
  background-color: cyan;
  display: none;
  position: relative;
}

.page2 {
  width: 100%;
  height: 100%;
  background-color: lime;
  display: none;
  position: relative;
}

.page-active {
  display: block;
}

a {
  color: black;
  position: absolute;
  top: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>

  <div class="page1" id="page1">
    hello
    <a href="#page2">go to page2</a>
  </div>
  <div class="page2" id="page2">
    hi
    <a href="#page1">go to page1</a>
  </div>
</body>

相关问题