一、要点
速度:var speed =(iTarget-cDiv1.offsetLeft)/10; //10为运动系数 缓缓运动
为了避免速度为小数:speed = speed>0?Math.ceil(speed):Math.floor(speed);
//如果速度大于0 向上取整;速度小于0向下取整
1<!DOCTYPE html> 2<html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 <style> 7 body,div,span{ 8 margin: 0; 9 padding: 0; 10 } 11 #div1{ 12 width: 200px; 13 height:200px; 14 background:red; 15 position: relative; 16 left: -200px; 17 } 18 #div1 span{ 19 width: 20px; 20 height: 100px; 21 background: blue; 22 position: absolute; 23 left: 200px; 24 top: 50px; 25 } 26 </style> 27 28 <script> 29 //Math.floor(9.99); //向下取整 9 30 //Math.ceil(9.9);//向上取整 10 31 var timer = null; 32 window.onload = function(){ 33 34 var cDiv1 = document.getElementById('div1'); 35 36 //鼠标移入 37 cDiv1.onmouseover = function(){ 38 startMove(0); //移动函数 39 } 40 41 //鼠标移出 42 cDiv1.onmouseout = function(){ 43 startMove(-200); //移动函数 44 } 45 46 /** 47 * @param {目标} iTarget 48 */ 49 function startMove(iTarget){ 50 51 clearInterval(timer); //为了避免定时器多次触发 52 53 var cDiv1 = document.getElementById('div1'); 54 timer = setInterval(function(){ 55 var speed =(iTarget-cDiv1.offsetLeft)/10; 56 //10为运动系数 缓缓运动 57 speed = speed>0?Math.ceil(speed):Math.floor(speed); 58 //如果速度大于0 向上取整;速度小于0向下取整 59 if(cDiv1.offsetLeft == iTarget){ 60 clearInterval(timer); //停止定时器 61 }else{ 62 cDiv1.style.left = cDiv1.offsetLeft+speed+'px'; //offsetLeft当前位置的值 63 } 64 },30) 65 }//每30毫秒动一下 66 } 67 68 69 </script> 70 </head> 71 <body> 72 <div id="div1"> 73 <span id="share">侧边广告</span> 74 </div> 75 </body> 76</html>