****
动画案例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);