天生勇气 2018-04-19
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>试验</title> <style> #div1{width:100px; height:100px; background:red; position:absolute; left:0px;top: 0px;} </style> <script type="text/javascript" src="move.js"></script> <script> window.onload=function(){ var oDiv=document.getElementById('div1'); var timer = null; var taskList = [ toRight, toLeft, toRight, toDown, toLeft, toTop, toDown, toRight, toTop, toLeft, ]; start(taskList); // Math.random(); function start (taskList){ var index = 0; doNext(index); function doNext (){ taskList[index](doNext); index++; if(index>=taskList.length){ index = 0; } } } oDiv.onclick = function() { clearInterval(timer); } function toRight(fn){ timer = setInterval(function (){ if(oDiv.offsetLeft<1100) { oDiv.style.left=oDiv.offsetLeft+40+'px'; } else { clearInterval(timer); fn(); } },30); } function toDown(fn){ timer=setInterval(function (){ if(oDiv.offsetTop<300) { oDiv.style.top=oDiv.offsetTop+40+'px'; } else { clearInterval(timer); fn(); } },30); } function toLeft (fn){ timer=setInterval(function (){ if(oDiv.offsetLeft>0) { oDiv.style.left=oDiv.offsetLeft-40+'px'; } else { clearInterval(timer); fn(); } },30); } function toTop(fn){ timer=setInterval(function (){ if(oDiv.offsetTop>0) { oDiv.style.top=oDiv.offsetTop-40+'px'; } else { clearInterval(timer); fn(); } },30); } } </script> </head> <body> <div id="div1" ></div> </body> </html>