jquery在滚动时固定侧栏,直到底部

Fra*_*aye 5 jquery scroll sidebar fixed

此代码取自waypointarts.com,它假设在滚动时创建一个侧边栏,直到底部.问题是当右div填充左div的高度,即使设置为100#保持固定到某个高度,窗口/屏幕或其他东西.如何将其设置为100%高度或相当于右div的高度.

HTML标头

<div id="wrapper">

  <div id="left">

    <div id="sidebar">

      Sidebar Content

    </div>

  </div>

  <div id="right">

    This is the text of the main part of the page.

  </div>

  <div class="clear"></div>

</div>

<div id="footer">Footer</div>
Run Code Online (Sandbox Code Playgroud)

CSS

#header {
  background: #c2c2c2;
  height: 50px
}

#wrapper {
  width: 500px
}

#left {
  background: #d7d7d7;
  position: absolute; /* IMPORTANT! */
  width: 150px;
  height: 100%
}

#right {
  position: relative;
  width: 350px;
  float: right
}

#sidebar {
  background: #0096d7;
  width: 150px;
  color: #fff
}

.clear {
  clear: both
}

#footer {
  background: #c2c2c2
}
Run Code Online (Sandbox Code Playgroud)

JAVASCRIPT

$(document).ready(function () {

    var length = $('#left').height() - $('#sidebar').height() + $('#left').offset().top;

    $(window).scroll(function () {

        var scroll = $(this).scrollTop();
        var height = $('#sidebar').height() + 'px';

        if (scroll < $('#left').offset().top) {

            $('#sidebar').css({
                'position': 'absolute',
                'top': '0'
            });

        } else if (scroll > length) {

            $('#sidebar').css({
                'position': 'absolute',
                'bottom': '0',
                'top': 'auto'
            });

        } else {

            $('#sidebar').css({
                'position': 'fixed',
                'top': '0',
                'height': height
            });
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

来自waypoitsarts.com的图片:

来自waypoitsarts.com的图片

Mar*_*k S 4

我认为你的脚本工作正常,可能问题出在你的 CSS 上。为了正确包含一个position:absolute;元素,您应该将其父元素 ( '#wrapper') 设置为position:relative

请参阅此 jsfiddle 上的演示:jsfiddle.net/J62Cp/