*{margin:0;padding:0;} 为什么不写这个,就停不下来了?

来源:2-1 JS速度动画

慕粉3755843

2018-03-23 17:57

<!DOCTYPE html>

<html>

<head>

<title>动画</title>

<style type="text/css">

#box{

width: 200px;

height: 100px;

background-color: black;

position: relative;

left:-200px;

}

#share{

width: 30px;

height: 50px;

background-color: blue;

position: absolute;

left:200px;

}

</style>

</head>

<body>

<div id="box"><span id="share"></span></div>

<script type="text/javascript">

window.onload=function(){

var odiv=document.getElementById('box');

odiv.onmouseover=function(){

startMove();

}

var timer=null;

function startMove(){

timer=setInterval(function(){

if(odiv.offsetLeft==0){

clearInterval(timer);

}

else{

odiv.style.left=odiv.offsetLeft+10+'px';

}

},30)

}

}

</script>

</body>

</html>


写回答 关注

1回答

  • hellf
    2018-03-25 17:07:15

    跟css中的{margin:0;padding:0;} 没有关系,你的代码中,判断offsetLeft 的条件改为: if(odiv.offsetLeft>=0)  它就停下来了 ,因为在不断移动的过程中,不一定有0这个值

    还有一个问题,进入startMove()时, 需要先清除一下定时器,目的是保证同时只有一个定时器在运行,你的代码还给你,就改了两个地方:

    <!DOCTYPE html>

    <html>

    <head>

    <title>动画</title>

    <style type="text/css">

    #box{

    width: 200px;

    height: 100px;

    background-color: black;

    position: relative;

    left:-200px;

    }

    #share{

    width: 30px;

    height: 50px;

    background-color: blue;

    position: absolute;

    left:200px;

    }

    </style>

    </head>

    <body>

    <div id="box"><span id="share"></span></div>

    <script type="text/javascript">

    window.onload = function() {

        var odiv = document.getElementById('box');

        odiv.onmouseover = function() {

            startMove();

        }

        var timer = null;

        function startMove() {

            clearInterval(timer);                // debug  1

            timer = setInterval(function() {

                console.log(odiv.offsetLeft)

                if (odiv.offsetLeft >= 0) {      //  debug 2

                    clearInterval(timer);

                } else {

                    odiv.style.left = odiv.offsetLeft + 10 + 'px';

                }

            },

            300)

        }

    }

    </script>

    </body>

    </html>



JS动画效果

通过本课程JS动画的学习,从简单动画开始,逐步深入各种动画框架封装

113931 学习 · 1443 问题

查看课程

相似问题