在页脚滚动到顶部时显示“返回顶部”

4

根据我看到的一些示例,我已经实现了一个返回顶部按钮,当你向下滚动页面时它可以出现并工作,不过有没有办法使该按钮一直保持在屏幕底部,直到你滚动到页脚,然后它会固定在页脚顶部?

这是我目前的代码:

<script type="text/javascript" defer="defer">
    $(window).scroll(function() {
        if ($(this).scrollTop()) {
            $("#toTop").fadeIn();
        } else {
            $("#toTop").fadeOut();
        }
    });


    $("#toTop").click(function() {
        $("html, body").animate({scrollTop: 0}, 1000);
    });
</script>

<style type="text/css">
    .backtotop_button_wrap {width:100%; background:white; height:auto;}
    .backtotop_button_height {width:100%; height:55px;}
    #toTop {display:none; position: fixed; right:0; bottom:0; width:100px; height:auto; background:white; float:right; padding:10px; text-align:center; border:1px solid black; line-height:12px;}
    #footer {width:100%; height:500px; color:white; text-align:center; background:#313131; border-top:1px solid black;}
</style>

<div class="backtotop_button_wrap">
    <div class="backtotop_button_height">
        <div id="toTop">^<br />Back to the Top</div>
    </div>
</div>
<div id="footer">
Footer
</div>

我也在这里制作了一个Jfiddle: http://jsfiddle.net/0Lge6wqq/


你需要让“返回顶部”按钮始终显示。 - sanoj lawrence
你的意思是让它停在页脚吗?还是要看到返回顶部框?因为在 jfiddle 中,如果你向下滚动预览面板,它应该会显示在底部的框,这正是我想要的,但是要在页脚开始滚动时停止。 - Chobbit
明白了。所以页脚应该将上面的框推上去? - Praveen Kumar Purushothaman
1个回答

8
将 #toTop 的html位置更改为 #footer。 当窗口到达页脚的高度时,#toTop 从固定变为相对。
     if($(window).scrollTop() + $(window).height() < $(document).height() - $("#footer").height()){
            $('#toTop').css("position","fixed");    //resetting it
            $('#toTop').css("bottom","0"); //resetting it
}
else {
            $('#toTop').css("position","relative"); // make it related
            $('#toTop').css("bottom","60px"); // 60 px, height of #toTop
 }

jsfiddle

http://jsfiddle.net/0Lge6wqq/4/


2
它可以正常运行,但最好切换类而不是切换样式。 - Jonathan Parent Lévesque

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接