JavaScript DOM编程艺术—javascript实现移动元素动画

将文档中的某个元素摆放到特定位置,并设置其移动至指定位置。

test.html

<!doucment html>
<html>
<body>
	<p id="message">Wheel!</p>
<script type="text/javascript" src="addLoadEvent.js"></script>
<script type="text/javascript" src="moveMessage.js"></script>
</body>
</html>

addLoadEvent.js

function addLoadEvent(func){
	var oldonload = window.onload;
	if(typeof oldonload != 'function'){
		window.onload= func;
	}
	else{
		oldonload();
		func();
	}
}

moveMessage.js

addLoadEvent(positionMessage);
//将元素指定到某个位置
function positionMessage(){
	var elem = document.getElementById('message');
	elem.style.position = "relative";
	elem.style.left="20px";
	elem.style.top="50px";
	elem.style.fontColor="red";
	moveMessage("message",200,100,10)
}
//将移动元素函数抽象
function moveMessage(elementID,end_x,end_y,interval){
	var elem = document.getElementById(elementID);
	var xpos = parseInt(elem.style.left);
	var ypos = parseInt(elem.style.top);
	if(xpos == end_x &&ypos == end_y){
		return true;
	}
	if(xpos < end_x){xpos++;}
	if(xpos > end_x){xpos--;}
	if(ypos < end_y){ypos++;}
	if(ypos > end_y){ypos--;}
	elem.style.left = xpos + "px";
	elem.style.top = ypos + "px";
	var repeat = "moveMessage('"+elementID+"',"+end_x+","+end_y+","+interval+")";
	movement = setTimeout(repeat,interval);
}


你可能感兴趣的:(JavaScript)