How do I get a fixed position div to scroll horizontally with the content? Using jQuery

后端 未结 3 715
暗喜
暗喜 2020-11-27 06:04

I have a div.scroll_fixed with the following CSS

.scroll_fixed {
    position:absolute
    top:210px

}
.scroll_fixed.fixed {
    position:fixed;
    top:0;
         


        
3条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 06:17

    The demo is keeping the element's position:fixed and manipulating the left property of the element:

    var leftInit = $(".scroll_fixed").offset().left;
    var top = $('.scroll_fixed').offset().top - parseFloat($('.scroll_fixed').css('margin-top').replace(/auto/, 0));
    
    
    $(window).scroll(function(event) {
        var x = 0 - $(this).scrollLeft();
        var y = $(this).scrollTop();
    
        // whether that's below the form
        if (y >= top) {
            // if so, ad the fixed class
            $('.scroll_fixed').addClass('fixed');
        } else {
            // otherwise remove it
            $('.scroll_fixed').removeClass('fixed');
        }
    
        $(".scroll_fixed").offset({
            left: x + leftInit
        });
    
    });
    

    Using leftInit takes a possible left margin into account. Try it out here: http://jsfiddle.net/F7Bme/

提交回复
热议问题