修复了两个div元素之间的div

时间:2017-05-29 07:20:23

标签: jquery css sticky

当滚动位置位于两个div元素之间时,我尝试创建一个固定的div元素。我使用此代码创建固定元素:

var sidebar = $('.sidebar').offset().top;

$(window).scroll(function() {  
    if ($(window).scrollTop() > sidebar) {
        $('.sidebar').addClass('fixed');
    }else{
        $('.sidebar').removeClass('fixed');
    }
});

我不知道如何在达到蓝色div时删除固定类。我试图获取蓝色div的当前位置并将其添加到if语句: var blueDiv = $('.bottom').offset().top

if ($(window).scrollTop() > sidebar && $(window).scrollTop() < blueDiv ){
    // add fixed class
}else{
    // remove fixed class
}

小提琴:https://jsfiddle.net/L7p5yeet/

2 个答案:

答案 0 :(得分:4)

当您检查侧边栏是否已到达蓝色div时,您忘记包括侧边栏的高度:

var sidebar = $('.sidebar').position().top;
var blueDiv = $('.bottom').position().top - $('.sidebar').innerHeight();

$(window).scroll(function() {
    var sT = $(window).scrollTop();
    if (sT > sidebar && sT < blueDiv) {
        $('.sidebar').addClass('fixed');
    }else{
        $('.sidebar').removeClass('fixed');
    }
});

答案 1 :(得分:4)

var sidebar = $('.sidebar').offset().top;
var blueOffset = $('.bottom').offset().top;
var sidebarHeight = $('.sidebar').height();
// If you reached the blue div (bottom), remove the 'fixed' class. Because the fixed element may not scroll over the footer or blue div. If you scroll back to the top (before the blue div or between the sidebar and the blue div) the fixed class need to be added again.
$(window).scroll(function() {
  if ($(window).scrollTop() > sidebar) {
    $('.sidebar').addClass('fixed');
  } else {
    $('.sidebar').removeClass('fixed');
  }
  if ($(window).scrollTop() > blueOffset - sidebarHeight) {
    $('.sidebar').removeClass('fixed');
  }
});
body {
  margin: 0;
  padding: 0;
}

.fixed {
  position: fixed;
  width: inherit;
  overflow: hidden;
  background: red;
  top: 0;
}

.topbar {
  background: red;
  height: 85px;
  text-align: center;
  line-height: 85px;
  color: #fff;
}

.container {
  width: 100%;
  overflow: hidden;
}

.left {
  float: left;
  width: 75%;
  background: gray;
  height: 800px;
}

.right {
  float: left;
  width: 25%;
  background: black;
  color: #fff;
}

.bottom {
  width: 100%;
  background: blue;
  overflow: hidden;
  height: 200px;
  line-height: 200px;
  color: #fff;
  text-align: center;
}

.footer {
  height: 600px;
  color: #000;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="topbar">
  <p>
    A simple topbar
  </p>
</div>
<div class="container">
  <div class="left">
    <p>
      Start fixed element
    </p>
  </div>
  <div class="right">
    <div class="sidebar">
      <ul>
        <li>Menu item 1</li>
        <li>Menu item 1</li>
      </ul>
    </div>
  </div>
  <div class="bottom">
    <p>
      Remove fixed element
    </p>
  </div>
</div>
<div class="footer">
  <p>
    A simple footer
  </p>
</div>