首页 文章

如何在滚动条上修复侧边栏?

提问于
浏览
0

我正在使用这个javaScript函数来修复右侧栏:

<script type="text/javascript">
$(document).ready(function () {  
    var top = $('#rightsidebar-wrapper').offset().top - parseFloat($('#rightsidebar-wrapper').css('marginTop').replace(/auto/, 0));
    $(window).scroll(function (event) {
        // what the y position of the scroll is
        var y = $(this).scrollTop();
        // whether that's below the form
        if (y >= top) {
           // if so, ad the fixed class
           $('#rightsidebar-wrapper').addClass('fixed');
        } else {
            // otherwise remove it
            $('#rightsidebar-wrapper').removeClass('fixed');
        }
    });
}); 
</script>

而这个CSS设计右侧栏div:

#rightsidebar-wrapper {
    background: #ffffff;
    width: 225px;
    float: right;
    margin-top: 8px 0px 0 0;
    padding:0px;
    word-wrap: break-word;
    overflow: hidden;
}

#rightsidebar-wrapper.fixed {
    position: fixed;
    top: 5px;

}

这是一个位于右侧的侧边栏 . The problem is that When the sidebar top meets the top-end of the screen on scrolling, it get floats to the left . 将此添加到CSS

right: 10%;

它修复了问题,但当页面被放大或缩小时,它再次失去了它的位置 . 知道如何解决这个问题吗?

2 回答

  • 0

    这是因为位置:固定是随浮动排出的 . 可能你必须绝对通过JavaScript设置位置 . 您可以使用$(window).resize()来修复放大/缩小问题 .

  • 0

    我知道这篇文章太旧了,但我希望将来有人在寻找这个没有Bootstrap的答案可能会觉得它很有用 . 它也适用于响应式网站 .

    首先,使用以下css属性创建一个div .

    #scroll_to{
        padding: 25px;
        display: inline-block;
        float: right;
        background-color: #eeeeee;
    }
    

    它将在窗口的右侧创建一个浮动框 .

    然后将此JS代码应用于您的div,它将工作 .

    Note: Please set the top: value according to your header bar

    var div_pos= $('#scroll_to').position().top;
    $(document).on('scroll', function() {
        var scroll_top= $(this).scrollTop();
        if(scroll_top>=div_pos){
            console.log("fix");
            $('#scroll_to').css({
                'position': 'fixed',
                'right': '0',
                'top': '36px'
            });
    
        }else{
            $('#scroll_to').css({
                'position': '',
                'right': '',
                'top': '36px'
            });
        }
    });
    

相关问题