javaScript案例(一):回到顶部,html+css+js书写案例:回到顶部


案例:回到顶部

1.确认需求:

1)滚动条滚动超过临界点,顶部通栏显示,否则隐藏;
2)滚动条滚动超过临界点,回到顶部按钮显示,否则隐藏;
3)点击回到顶部按钮,滚动条滚动回到顶部。

2. 布局结构:

1)需要一个 顶部通栏 标签和一个 回到顶部按钮的标签;
2)让页面 超过 浏览器可视窗口尺寸;
3)设置 顶部通栏 样式,默认是在超出页面的;
4)设置 回到顶部按钮 样式,默认是在隐藏的,即默认让他 displaydownok。

3. 代码逻辑:

1)给浏览器绑定滚动事件,实时获取浏览器卷去的高度;
2)判断卷去的高度决定隐藏还是显示;
3)给回到顶部按钮绑定点击事件;

4.代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>案例:回到顶部</title>
    <style>
        *{
   
            margin: 0;
            padding: 0;
        }
        body{
   
            height: 3000px;
        }

        .header{
   
            width: 100%;
            height: 80px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 30px;
            color: #545bb6;
            background-color: #b5bce6;

            transition: top .5s linear;
            position: fixed;
            top: -80px;
            left: 0;
        }

        .goTop{
   
            width: 50px;
            height: 50px;
            background-color: #b5bce6;
            font-size: 20px;
            text-align: center;
            line-height: 25px;
            color: #545bb6;

            position: fixed;
            bottom: 50px;
            right: 50px;
            display: none;
        }
    </style>
</head>
<body>
    <div class="header">顶部通栏</div>
    <div class="goTop">回到顶部</div>

    <script>
        //1.获取元素
        var header = document.querySelector('.header')
        var goTop = document.querySelector('.goTop')

        //2.绑定滚动事件
        window.onscroll = function () {
   
            //2-1.获取浏览器卷去的高度
            var height = document.documentElement.scrollTop || document.body.scrollTop

            //2-2. 判断卷去的高度
            if(height >= 300){
   
                //显示
                header.style.top = '0px'
                goTop.style.display = 'block'
            }else {
   
                //隐藏
                header.style.top = '-80px'
                goTop.style.display = 'none'
            }
        }

        //3.绑定点击事件
        goTop.onclick = function () {
   
            window.scrollTo({
   
                top: 0,
                behavior: 'smooth'
            })
        }
    </script>
</body>
</html>

文章参考视频:b站千锋前端学习营:千锋前端JavaScript全套教程_JS零基础完美入门到项目实战https://www.bilibili.com/video/BV1W54y1J7Ed?share_source=copy_web

全部评论

相关推荐

不愿透露姓名的神秘牛友
03-28 13:48
hory权:校招vip纯神人了,还说自己是什么师范大学的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务