javascript - 为什么setInterval里面offsetLeft undefined

查看:130
本文介绍了javascript - 为什么setInterval里面offsetLeft undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        *{
            margin: 0;
            padding: 0;
        }
        html,body{
            width: 100%;
            height: 100%;
        }
        .ball{
            width: 100px;
            height: 100px;
            border-radius: 50%;
            background: red;
            position: absolute;
            left: 100px;
            top:100px;
        }
    </style>
</head>
<body>
    <div class="ball"></div>
    <div class="ball"></div>
    <div class="ball"></div>

    <script>
        !function(){
            var ball=document.getElementsByClassName('ball');
            var speedX=[],speedY=[], left=[],right=[];
            for (var i = 0; i < ball.length; i++) {
                speedX[i]=parseInt(Math.random()*10);
                speedY[i]=parseInt(Math.random()*10);
                setInterval(function(){
                    left[i]=ball[i].offsetLeft;
                    top[i]=ball[i].offsetTop;

                    left[i]+=speedX[i];
                    top[i]+=speedY[i];

                    if (left[i]>document.body.offsetWidth-ball[i].offsetWidth||left[i]<=0) {
                        speedX[i]*=-1;
                        ball[i].style.background="rgb("+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+")";
                    }
                    if (top[i] >= document.body.offsetHeight - ball[i].offsetHeight || top[i] <= 0) {
                        speedY[i] *= -1;
                        ball[i].style.background = "rgb("+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+")";
                    }

                    ball[i].style.left=left[i]+'px';
                    ball[i].style.top=top[i]+"px";
                },5);
            }
        }()

    </script>
</body>
</html>

为什么 Uncaught TypeError: Cannot read property 'offsetLeft' of undefined???
该怎么修改??谢谢

解决方案

setInterval形成异步回调,因而,实际上最后执行的是

setInterval(function(){
                left[i]=ball[3].offsetLeft;
                \\other codes
            },5)

很明显 ball[3]是不存在的

解决方案则是想办法把i传进回调函数,并将其保存下来,可以参考

setInterval((function(i) {
    return function(){
      //code     
     }
})(i), 5)

这篇关于javascript - 为什么setInterval里面offsetLeft undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆