<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> div{ width: 300px;height: 200px; background-color: red; left: 50px; position: absolute; } </style> </head> <body> <input type="button" value="400px" id="bt1"> <input type="button" value="800px" id="bt2"> <div id="dv"> </div> <script type="text/javascript" src="tool.js"></script> <script> var div=my$("dv"); var timeID=0; //点击按钮时移动事件 my$("bt1").οnclick=function () { animate(dv,400) } my$("bt2").οnclick=function () { animate(dv,800) } function animate(e,l) { //1.获取当前些的位置current var current = div.offsetLeft; var timeID= setInterval(function () { //2.移动多少位置 var step = 10; step=l>current?step:-step; //3.最终移动到的位置.设置这个LEFT current += step //判断的思路:目标值-当前值是否大于移动的步数,如果 大于就向前走如果小于就把最终的位置设定成目标位置 if (Math.abs(l-current)>Math.abs(step)) { div.style.left = current + "px" } else { div.style.left = l + "px" clearInterval(timeID) } } ,20) } </script> </body> </html>
元素、对象称动案例
最新推荐文章于 2022-07-15 19:42:20 发布