移动元素到指定的位置
//HTML
<div id="test"></div>
//CSS
div{
width:100px;
height:100px;
background:red;
}
//js
/*将元素移动到300*300的位置*/
var elem = document.getElementById("test");
function moveElement(elementID,final_x,final_y,interval){
var elem = document.getElementById(elementID);
var xpos = parseInt(elem.style.left);
var ypos = parseInt(elem.style.top);
/*到达目的地left:300,top:300则退出函数*/
if(xpos==final_x && ypos ==final_y) {
return true;
}
/*小于300,加加*/
if(xpos<final_x){
xpos++;
}else if(xpos>final_x){
xpos--;
}
if(ypos<final_y){
ypos++;
}else if(ypos>final_y){
ypos--;
}
elem.style.left = xpos+"px";
elem.style.top = ypos+"px";
var repeat = "moveElement("+"'"+elementID+"'"+","+final_x+","+final_y+","+interval+")";
movement = setTimeout(repeat,interval);
}
function positionMessage(){
elem.style.left="460px";
elem.style.top="500px";
elem.style.position="absolute";
moveElement("test",300,300,10)
}
positionMessage();