HTML+Jquery实现返回顶部效果

141 Visits / 0 Comments / Favorite

最近在写博客的时候发现,文章内容过长翻起来太费劲,所以想看看有没有一键置顶功能。

因为涉及到前端操作,所以网上+gpt咨询了一下,给出的代码是可以运行的,遂把该功能添加进来。

show you my code

<div id="to_top">返回顶部</div>
<script src="/static/components/jquery/jquery.min.js"></script>
<style type="text/css">
    #to_top {
        width: 50px;
        height: 60px;
        padding: 10px;
        font: 14px/20px arial;
        text-align: center;
        background-color: #9999AA;
        color: #fff;
        /* 添加固定定位 */
        position: fixed;
        bottom: 20px; /* 距离视口底部20px */
        right: 20px; /* 距离视口右侧20px */
        /* 可选:添加一些阴影效果,使其看起来更突出 */
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
        /* 可选:添加一些过渡效果,使显示和隐藏更平滑 */
        transition: opacity 0.2s ease-in-out;
        /* 更改鼠标悬停时的形状 */
        cursor: pointer;
    }
</style>
<script>
    $(document).ready(function() {
        //首先将#btn隐藏
        $("#to_top").hide();
        //当滚动条的位置处于距顶部50像素以下时,跳转链接出现,否则消失
        $(function() {
            $(window).scroll(function() {
                if ($(window).scrollTop() > 100) {
                    $("#to_top").fadeIn(200);
                } else {
                    $("#to_top").fadeOut(200);
                }
            });
            //当点击跳转链接后,回到页面顶部位置
            $("#to_top").click(function() {
                $('body,html').animate({
                        scrollTop: 0
                    },
                    500);
                return false;
            });
        });
    });
</script>

效果图如下:

123.gif

All comments

Top