【问题标题】:How to fix a sidebar on scroll?如何修复滚动侧边栏?
【发布时间】:2017-09-09 16:02:35
【问题描述】:

我正在使用这个 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;

}

这是放置在右侧的侧边栏。 问题是当侧边栏顶部在滚动时遇到屏幕顶端时,它会向左浮动。将其添加到 CSS 中

right: 10%;

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

【问题讨论】:

  • 你能解决这个问题吗?我将元素设置为绝对并使用 JS 计算使其工作。我遇到的问题是 IE 在您滚动时会抖动。 Chrome 和 Firefox 都很流畅。我还必须让我的响应,所以设置一个权利或边距权利将无济于事。我的解决方案在这里:jsfiddle.net/yq3rcp0j/7

标签: javascript css html position


【解决方案1】:

那是因为 position: fixed 是用 float 排出的。可能你必须通过 JavaScript 绝对设置位置。您可以使用 $(window).resize() 来解决放大/缩小问题。

【讨论】:

    【解决方案2】:

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

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

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

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

    然后将这个 JS 代码应用到你的 div 中,它就会工作。

    注意:请根据您的标题栏设置top:

    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'
            });
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2017-10-07
      • 2019-05-06
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      • 2015-09-23
      • 1970-01-01
      相关资源
      最近更新 更多