jquery fixing a side bar while scrolling, until bottom

妖精的绣舞 提交于 2019-12-04 07:40:35

I think your script is working fine, probably the problem is on your CSS. In order to properly contain a position:absolute; element you should set its parent element ('#wrapper') to position:relative.

See the demo on this jsfiddle: jsfiddle.net/J62Cp/

I have a similar setup. I needed a "sticky" div that started at the top of the content section (300px below the top of the page, due to the header), was fixed while I scrolled down, but stopped when I got to a certain point (the footer). With pure CSS, the sticky div was going behind my footer after I got to the bottom. Your code got me going in the right direction, but here's the changes I made for my use case:

$(document).ready(function () {
    var length = $("#left").height() - $("#sidebar").height();

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

        if(scroll <= 0) {
            $("#sidebar").css({
                'position': 'absolute',
                'top': '0'
            });
        } else if(scroll >= length) {
            $("#sidebar").css({
                'position': 'absolute',
                'bottom': '0',
                'top': 'auto'
            });
        } else {
            $("#sidebar").css({
                'position': 'fixed',
                'top': '300px'
            });
        }
    });
});
Raajen

Do you want fixed positioned sidebar or sidebar with height = to main content part???? if you want height of sidebar equals to main content part, then this may help you..

$(function(){
   var mainHeight = $('.right').height();
      $('.left').css({
         'height':mainHeight
      });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!