JS:BOM应用_随着滚动条出现顶部通栏、返回顶部按钮

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        html,
        body {
            height: 2000px;
        }

        .banner {
            width: 100%;
            height: 0px;
            background-color: pink;
            position: fixed;
            top: 0;
            left: 0;
            font-size: 30px;
            display: flex;
            justify-content: center;
            align-items: center;
            color: aliceblue;
            overflow: hidden;
            transition: height .5s linear;
        }

        .btn {
            width: 100px;
            height: 50px;
            background-color: aqua;
            color: azure;
            display: flex;
            justify-content: center;
            align-items: center;
            position: fixed;
            right: 20px;
            bottom: 20px;
        }
    </style>
</head>

<body>
    <div class="banner">我是顶部通栏</div>
    <button class="btn" style="display: none;">返回顶部</button>

    <script>
        var banner = document.querySelector('.banner')
        var btn = document.querySelector('.btn')

        // window.onscroll  滚动条事件
        window.onscroll = function () {
            //window.scrollY 滚动条纵轴
            if (window.scrollY > 500) {
                // 出现顶部通栏   返回顶部按钮
                banner.style.height = "80px"
                btn.style.display = "block"
            } else {
                //隐藏顶部通栏    返回顶部按钮
                banner.style.height = "0px"
                btn.style.display = "none"
            }
        }

        //点击按钮返回顶部
        btn.onclick = function () {
            // setInterval 周期性定时器
            var timer = setInterval(function () {
                // document.documentElement.scrollTop   获取或设置一个元素的内容垂直滚动的像素数
                if (document.documentElement.scrollTop > 0) {
                    document.documentElement.scrollTop -=100
                } else {
                    document.documentElement.scrollTop = 0
                    // clearInterval 清除定时器
                    clearInterval(timer)
                }
            },
                40
            )
        }
    </script>
</body>

</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值