****
動畫案例1:
讓一個div隔5秒後開始向目的地(500,500)移動,到達目的地停止;
步驟;
1.獲得元素當前位置
2.如果元素已經到達目的地,則return true 結束函數;
3.反之,則改變left,top使他們更加靠近目的地;
4.經過一段時間後再通過setTimeout遞歸調用該函數;
<!-- HTML代碼 -->
<body>
<div id="moveDiv">我可以移動</div>
</body>
/*CSS代碼*/
div{
width: 100px;
height: 100px;
background-color: red;
position:absolute;
}
//JSd代碼:
function postionMessage(){
var moveDiv=document.getElementById("moveDiv");
//注意點1:style屬性值一定要注意加上”“引號,他是字符串
moveDiv.style.top="0px";
moveDiv.style.left="0px";
//setTimeout這個函數的第一個參數,是一個函數名,而且
// 是完整的,只是去掉花括號和裏面的內容,但是這個參數方法
//的參數列表也是要加上的,如果沒有參數,也要加上括號
setTimeout("moveMessage()",100);
}
function moveMessage(){
//通過parseInt來提取字符串中的數字
var xpos=parseInt(moveDiv.style.top);
var ypos=parseInt(moveDiv.style.left);
// alert("aa");
if(xpos==500&&ypos==500){
return true;
}
if(xpos<500){
xpos++;
}else{
xpos--;
}
if(ypos<500){
ypos++;
}else{
ypos--;
}
//一定要記得改變位置後要把新的位置返還給style屬性;
//這是又要注意style屬性值是字符串的,所以不要忘記加”px“
moveDiv.style.top=xpos+"px";
moveDiv.style.left=ypos+"px";
setTimeout("moveMessage()",10);
}
addLoadEvent(postionMessage);
****改進:
由於這個div移動函數只能制定特定的div進行移動,且移動的目的地和間隔時間是固定的;
假如我需要使這個移動函數具有靈活通用性的話,我需要去這個函數進行參數化改造:
根據上面的例子可知我們需要確定四個靈活通用的參數變量:
1、打算移動元素的ID;(elementId)
2.該元素的目的地left;(final_x)
3.該元素的目的地top;(final_y)
4.兩次移動之間的停頓時間;(interval)
<!-- HTML代碼 -->
<body>
<div id="moveDiv">我可以移動</div>
</body>
/*CSS代碼*/
div{
width: 100px;
height: 100px;
background-color: red;
position:absolute;
}
//JSd代碼:
function postionMessage(){
var moveDiv=document.getElementById("moveDiv");
//注意點1:style屬性值一定要注意加上”“引號,他是字符串
moveDiv.style.top="0px";
moveDiv.style.left="0px";
// alert("aa'");
//setTimeout這個函數的第一個參數,是一個函數名,而且
// 是完整的,只是去掉花括號和裏面的內容,但是這個參數方法
//的參數列表也是要加上的,如果沒有參數,也要加上括號
//現在moveMessage就是一個靈活通用性的方法了;
moveMessage("moveDiv",500,500,10);
}
function moveMessage(elementId,final_x,final_y,interval){
var moveDiv=document.getElementById(elementId);
//通過parseInt來提取字符串中的數字
var xpos=parseInt(moveDiv.style.top);
var ypos=parseInt(moveDiv.style.left);
// alert("aa");
if(xpos==final_x&&ypos==final_y){
return true;
}
if(xpos<final_x){
xpos++;
}else{
xpos--;
}
if(ypos<final_y){
ypos++;
}else{
ypos--;
}
//一定要記得改變位置後要把新的位置返還給style屬性;
//這是又要注意style屬性值是字符串的,所以不要忘記加”px“
moveDiv.style.top=xpos+"px";
moveDiv.style.left=ypos+"px";
//一定要注意在moveMessage中參數elementId是字符串,所以在做字符串拼接的時候一定要注意要額外爲其添加
//單引號以突出他是字符串,不然會出錯
var repeat="moveMessage('"+elementId+"',"+final_x+","+final_y+","+interval+")";
//這邊最好把setTimeout返回值給保存在movement中,便於清除
movement=setTimeout(repeat,interval);
}
addLoadEvent(postionMessage);