<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> *{ margin:0; padding:0; } ul{ list-style: none; } ul li{ width:200px; height: 80px; background: red; margin-bottom: 20px; border: 4px solid black; } </style> <script> window.onload=function(){ var Lis = document.getElementsByTagName("li"); for (var i = 0 ; i<Lis.length;i++){ Lis[i].timer = null; Lis[i].onmouseover = function(){ startMove(this,'width',400); }; Lis[i].onmouseout = function(){ startMove(this,'width',200); } } function startMove(obj,attr,target){ clearInterval(obj.timer); obj.timer = setInterval(function(){ var icur = parseInt(getStyle(obj,attr)); var speed = (target - icur)/8; speed = speed > 0 ? Math.floor(speed) : Math.ceil(speed); if(icur == target){ clearInterval(obj.timer); }else{ obj.style[attr] = icur + speed + "px"; } },30) } function getStyle(obj,attr){ if(obj.currentStyle){ return obj.currentStyle[attr]; }else{ return getComputedStyle(obj,false)[attr]; } } } </script> </head> <body> <ul> <li></li> <li></li> <li></li> </ul> </body> </html>
speed = speed > 0 ? Math.floor(speed) : Math.ceil(speed);
这一句换一下:
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
这样才能保证速度不为0;不然width差值小于8时速度就为0了,width就不变了,一直达不到200和400