效果:
思路:
首先,利用計時器setInterval實現DIV的隱藏顯示功能,然后在進行一個判斷,之后在把要移動的相應距離進行一個參數傳遞,再根據參數判斷出移動的方向也就是offsetLeft移動的方向,是正或者是負。最后利用onmouseover和onmouseout,實現DIV的事件。
代碼:
1 <head runat="server"> 2 <title></title> 3 <style type="text/css"> 4 div 5 { 6 width: 200px; 7 height: 300px; 8 background: #FF0000; 9 position: absolute; 10 left: -200px; 11 } 12 div span 13 { 14 width: 30px; 15 height: 90px; 16 background: #00FF00; 17 position: absolute; 18 right: -30px; 19 top: 100px; 20 text-align: center; 21 } 22 </style> 23 <script type="text/javascript"> 24 window.onload = function () { 25 var oDiv1 = document.getElementById('div1'); 26 oDiv1.onmouseover = function () { 27 shareMove(0); 28 } 29 oDiv1.onmouseout = function () { 30 shareMove(-200); 31 } 32 }; 33 var timer = null; 34 function shareMove(end) { 35 var oDiv1 = document.getElementById('div1'); 36 var speed = 0; 37 if (oDiv1.offsetLeft < end) { //根據DIV的offsetLeft距離判斷DIV所要走的正負方向 38 speed = 10; 39 } 40 else { 41 speed = -10; 42 } 43 clearInterval(timer); //在一個setInterval開始之前都要先清除之前的setInterval 44 timer = setInterval(function () { 45 if (oDiv1.offsetLeft == end) { //根據參數判斷DIV要走的距離 46 clearInterval(timer); 47 } 48 else { 49 oDiv1.style.left = oDiv1.offsetLeft + speed + 'px' //DIV要走的距離 50 } 51 }, 30); 52 } 53 </script> 54 </head> 55 <body> 56 <div id="div1"> 57 <span>青蘋果分享</span> 58 </div> 59 </body>