函数是指一段在一起的、可以做某一件事儿的程序。也叫做子程序、(OOP中)方法。
案例:移动元素,封装动画函数
1.div要移动,要脱离文档流---position:absolute
2.如果样式的代码是在style的标签中设置,外面是获取不到
3.如果样式的代码是在style的属性设置,外面是可以获取
4.获取div的当前位置
console.log(my$("dv").offsetLeft);
动画函数animate封装
*{
margin:0;
padding:0;
}
input{
margin-top:20px;
}
div{
margin-top:30px;
width:200px;
height:100px;
background-color:pink;
position:absolute;
}
//点击第一个按钮,移动到400px
my$("btn1").onclick=function(){
animate(my$("dv"),400);
};
//点击第二个按钮,移动到800px
my$("btn2").onclick=function(){
animate(my$("dv"),800);
};
//动画函数animate封装
functionanimate(element,target){
//先清理定时器
clearInterval(element.timeId);
//一会要清理定时器(只产生一个定时器)
element.timeId=setInterval(function(){
//获取div当前位置
varcurrent=element.offsetLeft;//数字类型,没有px
//div每移动多少像素---步数
varstep=10;
step=current //每次移动后的距离 current+=step; //判断当前移动后的位置,是否达到目标位置 if(Math.abs(target-current)>Math.abs(step)){ element.style.left=current+"px"; }else{ //清理定时器 clearInterval(element.timeId); element.style.left=target+"px"; } },20); }