搞了半天,要让元素动起来关键问题是要设置position属性,否则白费劲!!
不多说,上源码。
<!DOCTYPE html>
<html>
<head>
<title>flay</title>
</head>
<body>
<script>
window.οnlοad=function(){
var x = 10;//初始位置
var y = 10; //初始位置
var time = 0;//移动次数计数
var objMove = document.createElement("div");
objMove.id = "move";
objMove.style.width="100px";
objMove.style.height="100px";
objMove.style.top = y+"px";
objMove.style.left= x+"px";
objMove.style.backgroundColor="#0f0";
objMove.style.position = "absolute";//*require
document.body.appendChild(objMove);
var moveIt = function(){
time++;
if(time > 16){//移动一定次数后删除
document.body.removeChild(objMove);
moveIt = null;return;
}
x+=20;
y+=20;
objMove.style.top = y+"px";
objMove.style.left = x+"px";
if(moveIt){
setTimeout(moveIt, 100);
}
}
setTimeout(moveIt, 100);
}
</script>
</body>
</html>