jQuery回到顶部

本文介绍了一个使用jQuery实现的回到顶部按钮插件。该插件可根据滚动距离显示或隐藏回到顶部按钮,并通过平滑动画返回页面顶部。文章提供了完整的HTML、CSS样式及jQuery脚本代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

jQuery回到顶部

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Back to Top</title>
    <link rel="stylesheet" href="">
    <style>
        #content {
            height: 2000px;
        }
        #back-to-top.show {
            opacity: 1;
        }
        #back-to-top {
            position: fixed;
            bottom: 40px;
            right: 40px;
            z-index: 9999;
            width: 32px;
            height: 32px;
            text-align: center;
            line-height: 30px;
            background: #f5f5f5;
            color: #444;
            cursor: pointer;
            border-radius: 2px; 
            text-decoration: none;
            opacity: 0;
            transition: opacity .2s ease-out;
            border: 1px solid #ddd;
        }
    </style>
</head>
<body>
    <div id="content">Scroll &darr;</div>
    <a href="#" id="back-to-top" title="Back to top">&uarr;</a>

    <script src="jquery-1.9.0.min.js"></script>
    <script>
        if ($('#back-to-top').length) {
            var scrollTrigger = 100; // px

            // $(window).scrollTop()与 $(document).scrollTop()产生结果一样
            // 一般使用document注册事件,window使用情况如 scroll, scrollTop, resize
            $(window).on('scroll', function () {
                if ($(window).scrollTop() > scrollTrigger) {
                    $('#back-to-top').addClass('show');
                } else {
                    $('#back-to-top').removeClass('show');
                }
            });

            $('#back-to-top').on('click', function (e) {
                // html,body 都写是为了兼容浏览器
                $('html,body').animate({
                    scrollTop: 0
                }, 700);

                return false;
            });
        }
    </script>
</body>
</html>

 

转载于:https://www.cnblogs.com/loveyunk/p/6118269.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值