如何使div元素固定直到到达其他div

时间:2019-09-20 11:36:07

标签: javascript jquery html css

我正在为自己创建一个网站,我希望浏览器窗口附带上边框,直到它遇到下边框为止。

这是代码

.upperBorder {
  width: 100%;
  height: 40%;
  background-color: #EEECF5;
  -ms-transform: skewY(-5deg);
  /* IE 9 */
  -webkit-transform: skewY(-5deg);
  /* Safari 3-8 */
  transform: skewY(-5deg);
  box-shadow: 0 0 5px #333;
}

.lowerBorder {
  margin-top: 500px;
  width: 100%;
  height: 40%;
  background-color: #EEECF5;
  -ms-transform: skewY(-5deg);
  /* IE 9 */
  -webkit-transform: skewY(-5deg);
  /* Safari 3-8 */
  transform: skewY(-5deg);
  box-shadow: 0 0 5px #333;
}

div {
  display: block;
}
<div style="display:inline;" id="menu">
  <div class="img-container" data-slideshow style="position: fixed;">
    <img alt="img1" src="../Resources/Other/Pictures/1.jpg">
    <img alt="img2" src="../Resources/Other/Pictures/2.jpg">
    <img alt="img3" src="../Resources/Other/Pictures/3.jpg">
    <img alt="img4" src="../Resources/Other/Pictures/4.jpg">
    <img alt="img5" src="../Resources/Other/Pictures/5.jpg">
    <img alt="img6" src="../Resources/Other/Pictures/6.jpg">
    <img alt="img7" src="../Resources/Other/Pictures/7.jpg">
    <img alt="img8" src="../Resources/Other/Pictures/8.jpg">
    <img alt="img9" src="../Resources/Other/Pictures/9.jpg">
  </div>
  <div style="position: relative;height: 100vh;top:-150px;">
    <div class="upperBorder"></div>
    <div class="lowerBorder"></div>
  </div>
  <div class="logo"></div>
  <p class="Menu" style="left:50px;position: absolute;cursor: pointer;color: #EEECF5" onclick="">Home</p>
  <p class="Menu" style="left:15%;position: absolute;cursor: pointer;" onclick="">About Me</p>
  <p class="Menu" style="left:29%;position: absolute;cursor: pointer;" onclick="Projects()">Projects</p>

1 个答案:

答案 0 :(得分:0)

您可以通过比较偏移量来查看某个元素是否通过了另一个元素。参见下面的示例。

$(window).on('scroll', function(){
  var $fixedDiv = $('#FixedDiv');
  var $CollissionDiv = $('#ColissionDiv');
  
  //Get offset values (taking into account the height of the fixed div)
  var fixedDivCollisionPoint = $fixedDiv.offset().top + $fixedDiv.height();
  var ColossionDivOffset = $('#ColissionDiv').offset().top;
  
  //When collsion is detected set it div positioning to static
  if(fixedDivCollisionPoint > ColossionDivOffset) {
    $fixedDiv.css('position', 'static');
  }
});
#FixedDiv {
  position: fixed;
  top: 100px;
  border: 1px solid black;
}

#ColissionDiv {
  border: 1px solid red;
}

.NoColissionDiv {
  border: 1px solid green;
  height: 1000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class=NoColissionDiv>No Collision Div</div>
<div id=FixedDiv>Fixed Div</div>
<div id=ColissionDiv>Collision Div</div>
<div class=NoColissionDiv>No Collision Div</div>

相关问题