jquery經典例項之回到頂部

學習永遠不會晚發表於2020-12-07
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="GBK">
    <title>回到頂部</title>
    <style>
        .divA {
            height: 1500px;
        }
        .divB {
            width: 50px;
            height: 60px;
            font-size: 23px;
            background-color: green;
            position: fixed;
            right: 18px;
            bottom: 18px;
        }
        .divB:hover{
            cursor: pointer;
        }
        .hide {
            display: none;
        }
    </style>
</head>
<body>
    <div class="divA"></div>
    <div class="divB hide" onclick="gotoTop()"><strong>回到頂部</strong></div>

    <script src="jquery-1.5.1.js"></script>
    <script>
        window.onscroll = function () {
            var current = $(window).scrollTop();
            //縱向滾動條遮蓋高度超過180就顯示回到頂部div
            if (current > 180){
                $(".divB").removeClass("hide");
            }else {
                $(".divB").addClass("hide");
            }
        };

        function gotoTop() {
            $(window).scrollTop(0);
        }
    </script>
</body>
</html>

 

相關文章