js---小火箭回到顶部

比较粗糙,能到到效果,点击小火箭回到顶部,期间有小火箭的特效,

用到了css3的动画,JS的滚动事件

 

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #firetop {
            width: 148px;
            height: 250px;
            background: url(https://images.cnblogs.com/cnblogs_com/muyun123/1532955/o_rocket_button_up.png);
            cursor: pointer;
            position: fixed;
            bottom: 0;
            right: 0;
            transition: bottom 1s;
            display: none;
        }

        #firetop:hover {
            background-position: -148px 0;
        }

        body {
            width: 100%;
            height: 7000px;
        }

        @keyframes move {
            0% {
                background-position: -296px 0;
            }
            100% {
                background-position: -892px 0;
            }
        }
    </style>

</head>

<body>
    <div id="firetop"></div>
</body>
<script>
    (function () {
        var firetop = document.getElementById('firetop');
        //当有滚动时触发事件
        window.onscroll = function () {
            var num = window.scrollY;//获取滚动条的移动距离
            var num1 = window.innerHeight;//屏幕可视区的高度
            if (num > 200) {
                firetop.style.display = 'block';//让回到顶部的小火箭出现
            } else if (num <= 0) {
                firetop.style.bottom = num1 + 'px';//改变定位的位置
            }
        }
        //点击事件
        firetop.onclick = function () {
            var scrolltop = window.scrollY;
            var timer = setInterval(function () {//定时器启动
                scrolltop -= 50;                   
                if (scrolltop <= -window.innerHeight) {
                    firetop.style.display = 'none'; //小火箭隐藏
                    firetop.style.animation = '';   //清除动画
                    firetop.style.bottom = 0 + 'px';    //还原小火箭位置
                    clearInterval(timer);
                }
                window.scrollTo(0, scrolltop);//设置滚动条距离顶部的距离
            }, 30);
            this.style = 'animation:move 2s steps(4, end) infinite;'//给动画
        }

    })();
</script>

</html>

猜你喜欢

转载自www.cnblogs.com/muyun123/p/11431547.html