动画函数的封装
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> #dv { height: 200px; width: 200px; background-color:pink; position: relative; left: 0; top: 0; } </style> </head> <body> <input type="button" value="移动到400px" id="btn1"> <input type="button" value="移动到800px" id="btn2"> <div id="dv"></div> <script src="common.js"></script> <script> //设置任意一个元素移动到任意位置 function animate(element,target){ clearInterval(element.timer); element.timer=setInterval(function(){ var current=element.offsetLeft; var step=10; step=current<target?step:-step; current+=step; if(Math.abs(current-target)>Math.abs(step)){ element.style.left=current+"px"; }else{ clearInterval(element.timer); element.style.left=target+"px"; } },100); } my$("btn1").οnclick=function () { animate(my$("dv"),400); }; my$("btn2").οnclick=function () { animate(my$("dv"),800); }; </script> </body> </html>