固定与其父

时间:2016-09-05 16:44:22

标签: javascript jquery html css css3

我有这个片段,但我需要将红色框限制为不会出现的白色框。



.main {
  background-color: black;
  width: 100%;
  height: 1250px;
  position: relative;
}

.container{
  display: block;
  position: absolute;
  width: 250px;
  height: 650px;
  background: white;
}

.red-box{
  background: red;
  width: 150px;
  height: 140px;
  position: fixed;
}

<div class="main">
  <div class="container">
    <div class="red-box">
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:5)

由于red-box已经fixed,因此请修复container - 希望这可以解决您的问题。干杯!

&#13;
&#13;
body {
  margin: 0;
}
.main {
  background-color: black;
  width: 100%;
  height: 1250px;
  position: relative;
}
.container {
  display: block;
  position: fixed;
  width: 250px;
  height: 650px;
  background: white;
}
.red-box {
  background: red;
  width: 150px;
  height: 140px;
  position: fixed;
}
&#13;
<div class="main">
  <div class="container">
    <div class="red-box">
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

修改

希望这个引脚 - red-div使用jquery滚动出container

&#13;
&#13;
$(document).scroll(function() {
  var wrapper = $('.container');
  var box = $('.red-box');

  var offset = wrapper.offset().top - $(window).scrollTop() + wrapper.outerHeight() - box.outerHeight();


  if (offset >= 0) {
    box.css({
      'top': 0
    });
    return;
  }

  box.offset({
    'left': box.offset().left,
    'top': $(window).scrollTop() + offset
  });


});
&#13;
body {
  margin: 0;
}
.main {
  background-color: black;
  width: 100%;
  height: 1250px;
  position: relative;
}
.container {
  display: block;
  position: absolute;
  width: 250px;
  height: 650px;
  background: white;
}
.red-box {
  background: red;
  width: 150px;
  height: 140px;
  position: fixed;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <div class="container">
    <div class="red-box">
    </div>
  </div>
</div>
&#13;
&#13;
&#13;