页面返回顶部和固定导航栏js基础案例

案例代码​​​​​​​

<!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>
        * {
            padding: 0;
            margin: 0;
            box-sizing: border-box;
        }

        .content {
            margin: 0 0 0 200px;
            overflow: hidden;
            width: 800px;
            height: 3000px;
            background-color: skyblue;
            float: left;
        }

        .backtop {
            margin-left: 1000px;
            margin-top: 550px;
            width: 30px;
            position: fixed;
            float: left;
        }

        .backtop .icon {
            height:50px;
            width: 50px;
            display: none;
            opacity: 0.3;
        }

        .header {
            position: fixed;
            top: -80px;
            left: 0;
            width: 100%;
            height: 80px;
            background-color: pink;
            text-align: center;
            color: white;
            line-height: 80px;
            font-size: 20px;
            transition: all .3s;
        }

        .miaosha {
            width: 300px;
            height: 300px;
            background-color: sandybrown;
            margin-top: 500px;
            color: brown;
        }
    </style>
</head>
<body>
    <div class="header">我是顶部导航栏</div>
    <div class="content">
        <div class="miaosha">秒杀模块</div>
    </div>
    <div class="backtop">
        <img class="icon" src="./image/箭头.jpg">
    </div>
    <script>
        // 1、页面滚动事件
        let miaosha = document.querySelector('.miaosha')
        let header = document.querySelector('.header')
        let backtop = document.querySelector('.backtop')
        let icon = document.querySelector('.icon')
        window.addEventListener('scroll',function(){

            if(document.documentElement.scrollTop >= backtop.offsetTop){
               icon.style.display = 'block'
               } else{
                icon.style.display = 'none'
               }
            // console.log(document.documentElement.scrollTop)
            // 2、要检测滚动的距离 >= 秒杀模块的offsetTop值 则滑入
            // console.log(miaosha.offsetTop) 
            if( document.documentElement.scrollTop >= miaosha.offsetTop){
             header.style.top = '0'
            }else{
             header.style.top = '-80px'   
            }
        })
         // 回到顶部
        backtop.addEventListener('click',function(){
            document.documentElement.scrollTop = 0
         })
    </script>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值