精灵图-学习记录

发布于 2020-04-22  119 次阅读


效果

进网页查看:传送门

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="move.js"></script>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
    <style>
        body{
            margin: 0;
            padding: 0;
        }
        .bodyy{
            width: 100vw;
            height: 100vh;
            background-color: #ccc;
        }
        .backtop {
            position: absolute;
            top: 50%;
            /*left: 50%;*/
            z-index: 322;
            clear: both;
            margin-top: -50px;
            margin-left: -63px;
            width: 68px;
            height: 100px;
            background: url(backtop.png);
            background-position: 0px 0px;
        }
        .bo{
            width: 1200px;
            height: 100vh;
            background-color: #fff;
            margin:auto;
            position: relative;
        }
    </style>
</head>
<body>
    <div class="bodyy">
        <div class="bo">
            <div class="backtop">
            </div>
        </div>
    </div>
    
    <script>
        var y=0;
        var t;
        $(function(){
            var $s=$('.backtop');
            $s[0].onmouseover=function(){
                y=0;
                clearInterval(t);
                t=setInterval(function(){
                    $s.css({
                        backgroundPosition: '0px '+y+'px'
                    });
                    y-=100;
                    if(y%1100==0){clearInterval(t);}      
                    console.log(typeof $s[0].style.backgroundPosition);
                },50);
            };
            $s[0].onmouseout=function(){
                clearInterval(t);
                t=setInterval(function(){
                    y-=100;
                    $s.css({
                        backgroundPosition: '0px '+y+'px'
                    });         
                    if(y==-1400){
                        clearInterval(t);
                    }
                    console.log($s[0].style.backgroundPosition);
                },50);
            };
            console.log($s);
        });
    </script>
</body>
</html>
  • 虽然案例比较简单,但是定时器叠加问题还是耗费了我不少时间
  • 最后解决了定时器叠加问题,并且有了更多的理解