左列固定,直到右列可滚动

时间:2018-01-15 23:48:35

标签: scroll

this web page一样,我想在我的布局中有一个由2列组成的部分:当scrollTop到达部分的上边距时,左列保持固定,右列垂直移动,直到它的下边距出现了。从这里向下,他们都可以正常移动。

她是怎么做到的?有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

https://codepen.io/perminder-klair/pen/tdzue

$( document ).ready(function() {
  console.log( "document ready!" );

  var $sticky = $('.sticky');
  var $stickyrStopper = $('.sticky-stopper');
  if (!!$sticky.offset()) { // make sure ".sticky" element exists

    var generalSidebarHeight = $sticky.innerHeight();
    var stickyTop = $sticky.offset().top;
    var stickOffset = 0;
    var stickyStopperPosition = $stickyrStopper.offset().top;
    var stopPoint = stickyStopperPosition - generalSidebarHeight - stickOffset;
    var diff = stopPoint + stickOffset;

    $(window).scroll(function(){ // scroll event
      var windowTop = $(window).scrollTop(); // returns number

      if (stopPoint < windowTop) {
          $sticky.css({ position: 'absolute', top: diff });
      } else if (stickyTop < windowTop+stickOffset) {
          $sticky.css({ position: 'fixed', top: stickOffset });
      } else {
          $sticky.css({position: 'absolute', top: 'initial'});
      }
    });

  }
});
.container {
  width: 1000px;
  position: relative;
}

.header {
  clear: both;
  margin-bottom: 10px;
  border: 1px solid #000000;
  height: 90px;
}

.sidebar {
  float: left;
  width: 350px;
  border: 1px solid #000000;
}

.content {
  float: right;
  width: 640px;
  border: 1px solid #000000;
  height: 800px;
}

.footer {
  clear: both;
  margin-top: 10px;
  border: 1px solid #000000;
  height: 820px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="header">
    This is header
  </div>
  <div class="sidebar sticky">
    This is side bar
  </div>
  <div class="content">
    This is main content
  </div>
  <div class="footer">
    <div class="sticky-stopper"></div>
    This is my footer
  </div>
</div>

请检查一下。它sw水帮助你。