速度:var speed =(iTarget-cDiv1.offsetLeft)/10; //10为运动系数 缓缓运动html
为了不速度为小数:speed = speed>0?Math.ceil(speed):Math.floor(speed);
//若是速度大于0 向上取整;速度小于0向下取整函数
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> body,div,span{ margin: 0; padding: 0; } #div1{ width: 200px; height:200px; background:red; position: relative; left: -200px; } #div1 span{ width: 20px; height: 100px; background: blue; position: absolute; left: 200px; top: 50px; } </style> <script> //Math.floor(9.99); //向下取整 9 //Math.ceil(9.9);//向上取整 10 var timer = null; window.onload = function(){ var cDiv1 = document.getElementById('div1'); //鼠标移入 cDiv1.onmouseover = function(){ startMove(0); //移动函数 } //鼠标移出 cDiv1.onmouseout = function(){ startMove(-200); //移动函数 } /** * @param {目标} iTarget */ function startMove(iTarget){ clearInterval(timer); //为了不定时器屡次触发 var cDiv1 = document.getElementById('div1'); timer = setInterval(function(){ var speed =(iTarget-cDiv1.offsetLeft)/10; //10为运动系数 缓缓运动 speed = speed>0?Math.ceil(speed):Math.floor(speed); //若是速度大于0 向上取整;速度小于0向下取整 if(cDiv1.offsetLeft == iTarget){ clearInterval(timer); //中止定时器 }else{ cDiv1.style.left = cDiv1.offsetLeft+speed+'px'; //offsetLeft当前位置的值 } },30) }//每30毫秒动一下 } </script> </head> <body> <div id="div1"> <span id="share">侧边广告</span> </div> </body> </html>