計時器的應用

cosmos033發表於2018-05-26

<script src="myjs.js"></script>

<script>

var oul = document.getElementsByTagName("ul")[0];
var str = "";
for(var i=0;i<20;i++){
str += "<li></li>";
}
oul.innerHTML = str;
var ali = document.getElementsByTagName("li");
for(var i=0;i<ali.length;i++){
ali[i].style.left = i*51+"px";
}
var j = 0;
document.onclick = function(){
var timer = setInterval(function(){
doMove(ali[j],7,500,"top");
j++;
j==20 && clearInterval(timer);
},200)
}

</script>


-----------------------------------------------myjs.js-----------------------------------------------------

function doMove(obj,step,end,attr,endFn){
step = parseInt(getStyle(obj,attr)) > end ? -step : step;
clearInterval(obj.timer);
obj.timer = setInterval(function (){
var nextL = parseInt(getStyle(obj,attr))+step;
if(nextL>=end&&step>0||nextL<=end&&step<0){
nextL = end;
}
obj.style[attr] = nextL+"px";
if(parseInt(getStyle(obj,attr))==end){
clearInterval(obj.timer);
//if(endFn){endFn();}
endFn && endFn();
}
},30)
}

相關文章