滚动到顶部时,侧栏会消失

时间:2015-09-26 04:40:39

标签: jquery css sidebar scrolltop

我现在正在这个网站上工作,我在侧边栏上按下直到我点击页脚。

DEMO SITE ID:test PASS:2015

我做得很好,但是当我滚动到顶部(非常顶部)时,我的侧栏将自己隐藏起来。

side bar disappears...

当我向后滚动一点点或点击F5并刷新它会再次出现。

这是我用于此功能的javascript。

$(function(){
var target = $("#subContainer");//select which element you want to follow
var footer = $("footer")//making sidebar stop at footer
var targetHeight = target.outerHeight(true);
var targetTop = target.offset().top;

$(window).scroll(function(){
    var scrollTop = $(this).scrollTop();
    if(scrollTop > targetTop){
        var footerTop = footer.offset().top;

        if(scrollTop + targetHeight > footerTop){
            customTopPosition = footerTop - (scrollTop + targetHeight)
            target.css({position: "fixed", top:  customTopPosition + "px"});
        }else{
            target.css({position: "fixed", top: "10px"});
        }
    }else{
        target.css({position: "static", top: "auto"});
    }
});

});

如何解决此问题,以便在我向上滚动时显示侧边栏。

感谢您的时间!

2 个答案:

答案 0 :(得分:1)

当页面滚动到达页面顶部时,您只需将其样式恢复为默认值。在这种情况下,该解决方案可用于解决问题。

将上面的代码替换为:

$(function(){
var target = $("#subContainer");//select which element you want to follow
var footer = $("footer")//making sidebar stop at footer
var targetHeight = target.outerHeight(true);
var targetTop = target.offset().top;

$(window).scroll(function(){
    var scrollTop = $(this).scrollTop();
    if(scrollTop > targetTop){
        var footerTop = footer.offset().top;

        if(scrollTop + targetHeight > footerTop){
            customTopPosition = footerTop - (scrollTop + targetHeight)
            target.css({position: "fixed", top:  customTopPosition + "px"});
        }else{
            target.css({position: "fixed", top: "10px"});
        }
    }else{
        target.removeAttr("style"); // change is made here
    }
});

});

答案 1 :(得分:1)

而不是:

target.css({position: "static", top: "auto"});

只需将顶部css重置为0px:

target.css({top: "0px"});

这是因为我们在第一次加载页面时#subContainer上的原始样式已经有position: fixed。所以真正唯一改变的是最高位置价值。

您应该只需更改顶部即可进一步简化代码:

$(window).scroll(function(){
    var scrollTop = $(this).scrollTop();
    if(scrollTop > targetTop){
        var footerTop = footer.offset().top;

        if(scrollTop + targetHeight > footerTop){
            customTopPosition = footerTop - (scrollTop + targetHeight)
            target.css({top:  customTopPosition + "px"});
        }else{
            target.css({ top: "10px"});
        }
    }else{
        target.css({top: "0px"});
    }
});