<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> <style> div{ height: 200px; width: 100px; background-color: red; margin: 20px; float: left; } </style> <script type="text/javascript"> window.onload = function() { var dv = document.getElementsByTagName('div'); //给DIV绑定鼠标移入事件 for(var i=0;i<dv.length;i++){ dv[i].timer = null; dv[i].onmouseover = function(){ starMove(this,'width',500) } } //创建一个获取外部样式的函数 function getStyle(obj,name){ if(obj.currentStyle){ return obj.currentStyle[name]; }else { return getComputedStyle(obj,false)[name]; } } //运动函数 function starMove(obj,atr,target){ clearInterval(obj.timer); var cur = parseInt(getStyle(obj,atr)) obj.timer = setInterval(function(){ var speed = (target - cur)/6; speed = speed>0?Math.ceil(speed):Math.floor(speed); if(cur==target){ clearInterval(obj.timer) }else { obj.style[atr] = cur + speed +'px'; } },30); } } </script> </head> <body> <div id="d1"></div> <div id="d2"></div> <div id="d3"></div> </body> </html>
运行后无法正确执行运动= = 定时器只能执行一次 就只移动一下 再移入还是会移动 最终会到500 球各位大神找下错误 感激不尽
OlderSkee
相关分类