【问题标题】:stops sidebar scrolling when its reach bottom of the page当侧边栏到达页面底部时停止滚动
【发布时间】:2014-07-17 07:40:26
【问题描述】:

我正在开发一个带有粘性侧边栏的网站。侧边栏只会固定在滚动窗口上。

问题是,当我向下滚动窗口并到达页面底部时,边栏将与页脚重叠,因为边栏是固定的。

我希望,当用户到达页面底部时,侧边栏停止滚动,如果用户正在滚动页面顶部,它应该再次开始滚动。

您可以在下面查看我的代码,也可以查看fiddle here

脚本

<script>
$(window).scroll(function(){

        var contPos = $('.sidebar').offset().top;       

        var containerHeight = $('.container').height();

        var heightOfWindow = $('body').height();            
        var topOfWindow = $(window).scrollTop();

            if (contPos < topOfWindow) {
                $('.sidebar').css('margin-top',''+topOfWindow+'px');

            }
    }); 


</script>

HTML

<div class="header">Header</div>
<div class="sidebar">asd</div>
<div class="container">Contaier</div>
<div class="footer">Footer</div>

CSS

.header{height:100px; text-align:center; font-size:35px; color:#000; background:#999;}
.container{overflow:auto; padding:15px; background:#CCC; height:1000px; margin:0 0 0 300px;}
.sidebar{width:300px; height:700px; float:left; background:red;}
.footer{height:100px; text-align:center; font-size:35px; color:#000; background:#999;}

【问题讨论】:

  • 为什么要使用javascript?在我看来,您想为侧边栏使用类似 position:fixed 的东西
  • “侧边栏停止滚动,如果用户正在滚动页面顶部,它应该再次开始滚动” - 如果它滚动,那么“固定”是什么意思?您在哪里尝试创建类似this 的东西?我没有得到你想要做什么。
  • 我希望当用户到达页面底部时侧边栏不会超过页脚......当用户从页面底部滚动到顶部时,侧边栏应该开始浮动。

标签: jquery html css scroll sidebar


【解决方案1】:

我猜你必须编写一个 JS 代码来检测侧边栏是在页面的顶部、底部还是中间。然后你可以设置一个特定的css类“底部”,“顶部”,..并在fixed/absolute之间设置正确的位置。

我会这样做:

http://jsfiddle.net/w6G7Z/1/

【讨论】:

    【解决方案2】:

    在这种情况下,可以很容易地解决最初的问题,方法是给侧边栏的 CSS 类 position:absolute 并设置 top 属性而不是 margin-top

    css:

    .sidebar{
        width:300px; 
        height:700px; 
        float:left; 
        background:red;
        position:absolute;
    }
    

    javascript:

    if (contPos < topOfWindow) 
    {
        $('.sidebar').css('top',topOfWindow+'px');
    }
    

    见小提琴here

    但是,当您向上滚动时,您仍然会遇到问题。

    【讨论】:

    • 感谢帮助我希望当用户到达页面底部时侧边栏不会超过页脚......当用户从页面底部滚动到顶部时,侧边栏应该开始浮动。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多