jQuery回到顶部

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