<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{box-sizing: border-box;} #box1{ 900px;height: 150px;border: 1px solid black;position: relative;} #box2{ 900px;height: 150px;border: 1px solid black;position: relative;margin-top: 10px;} #obox1{ 100px;height: 100px;background-color: red;margin-top: 25px;position: absolute;left: 0;top: 0;} #obox2{ 100px;height: 100px;background-color: red;margin-top: 25px;position: absolute;left: 0;top: 0;} </style> </head> <body> <div id="box1"> <div id="obox1"> </div> </div> <div id="box2"> <div id="obox2"> </div> </div> </body> <script type="text/javascript"> var box1 = document.querySelector("#box1"); var box2 = document.querySelector("#box2"); var obox1 = document.querySelector("#obox1"); var obox2 = document.querySelector("#obox2"); box1.onmouseenter = function(){; move(obox1,{left:600,top:150},function(){ alert("结束了") }) } box1.onmouseleave = function(){; move(obox1,{left:0,top:10}) } box2.onmouseenter = function(){; move(obox2,{left:0,top:300}) } box2.onmouseleave = function(){; move(obox2,{left:0,top:10}) } function move (ele,obj,callback){ clearInterval(ele.t); ele.t = setInterval(function(){ var onoff = true; for(var i in obj){ var now = parseInt(getStyle(ele,i)); speed = (obj[i]-now)/7; speed = speed>0? Math.ceil(speed):Math.floor(speed); if(obj[i]!=now){ onoff = false; } ele.style[i]=now+speed+"px"; } if(onoff){ clearInterval(ele.t); //如果没有实参传入,会显示undefined,则不执行,去过有实参传入,会执行实参 callback && callback(); } },30) } function getStyle(ele,attr){ if(ele.currentStyle){ return ele.currentStyle[attr]; }else{ return getComputedStyle(ele,false)[attr]; } } </script> </html>