首页 > js运动点击不能匀速

js运动点击不能匀速

新手求助,看了一个视频,根据上面的内容写了一个运动的事件,因为在点击时会多开定时器,导致越走越快,我就在开始写了一个清除定时器,但是还是越走越快,麻烦大神指点一下是哪里出了问题。

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        #div1{
            width: 200px;
            height: 200px;
            background-color: red;
            position: absolute;
            top: 50px;
            left: 0px;
        }
    </style>
    <script>
        window.onload=function()
        {
            
            var myb1=document.getElementById('b1');
            myb1.onclick=function()
            {
                
                var mydiv=document.getElementById('div1');
                var speed=1;
                var timer=null;
                **clearInterval(timer);**
                timer=setInterval(function(){
                    if(mydiv.style.left=='300px')
                    {
                        clearInterval(timer);
                    }
                    else
                    {
                        mydiv.style.left=mydiv.offsetLeft+speed+'px';
                    }
                    

                }, 30);
            }
        }
        
    </script>
</head>
<body>
    <button id="b1">开始运动</button>
    <div id="div1">
        
    </div>
</body>
</html>

把timer变量设定为全局变量 你定义在onclick的function内 是局部变量
按你的定义 每次一点击 timer就被重置为null了,定时器依然在继续工作,起不到作用

把timer定义到

window.onload=function(){
    var timer
}

你每次点击,导致变量timer都被重新定义值为null,而serInterval依然运行。

【热门文章】
【热门文章】