我在做一个写个练习,生成一排div后,依次下落,当最后一个div落到目标点后,再从第一个div依次往上飞回原来的位置。这是我写的代码
请输入代码
window.onload=function(){
var str=document.createElement("div");
var len=10;
for(var i=0;i<len;i++){
str.innerHTML += '<div style="width:50px;height:50px;background:red;border-radius:50px;position:absolute;top:0px;left:'+i*50+'px"></div>';
}
document.body.appendChild(str);
alert(str.style.width)
var aDiv=str.getElementsByTagName("div");
function fall(obj,v,target,callback){
v= obj.offsetTop<target? v :-v //此处不停报错说can't read //property "offsetTop" of undefined;
clearInterval(obj.timer);
obj.timer=setInterval(function(){
var top=obj.offsetTop+v;
if(top>target&&v>0||top<target&&v<0){
top=target;
}
obj.style.top=top+"px";
if(top==target){
clearInterval(obj.timer);
callback&&callback();
}
},50)
}
var num=0;var timer=null;
document.onclick=function(){
clearInterval(timer);
var flag=true;
timer = setInterval(function () {
if (flag) {
fall(aDiv[num], 20, 500);
num++;
if (num == aDiv.length/*//aDiv[aDiv.length-1].offsetTop===500*/) {
flag = false;
num = 0;
}
} else {
fall(aDiv[num], 20, 0)
num++;
}
}, 60)
}
}```
目前找到一个错误。你在else部分未作长度判断
导致
num=10;
aDiv
的索引只到9,aDiv[10]
为undefined
,所以报错。补充:
根据你的逻辑我贴下修改后的代码
可以自己再优化下。