js實現基礎運動

來源:互聯網
上載者:User

標籤:

首先我定義3個div每個div當我滑鼠放上去的時候,他的寬度就表達,如

首先是樣式和html代碼

 1 <style> 2     div{ 3         width:100px; 4         height:50px; 5         background:red; 6         margin-bottom:10px; 7     } 8 </style> 9 10 <body>11     <div></div>12     <div></div>13     <div></div>14 </body>

js代碼如下,帶注釋

 1 <script> 2 //重點是給每個對象加個定時器 3     window.onload=function() 4     { 5         var div1= document.getElementsByTagName(‘div‘);  //擷取每個div 6          7         for(var i=0;i<div1.length;i++)  //當移到哪個div,哪個div發生變化 8         { 9             div1[i].timer=null;     //首先將定時器清空以免發生其他問題10             div1[i].onmouseover=function()11             {   12                 startMove(this,400);13             };14             div1[i].onmouseout=function()15             {16                  startMove(this,100);  17             };18         }19     };20     21     function startMove(obj,iTarget)22     {23        clearInterval(obj.timer);24        obj.timer=setInterval(25         function()26         {27             var speed=(iTarget-obj.offsetWidth)/5;  // 定義速度28           29             speed=speed>0?Math.ceil(speed):Math.floor(speed);  //速度去上限的限30             if (obj.offsetWidth==iTarget)    //如果寬度已經增加到需要的寬度。停止計時器31             {32                 clearInterval(obj.timer);33             }34             else         //不斷增加寬度直到到iTarget的值35             {36                 obj.style.width=obj.offsetWidth+speed+‘px‘;37             }38 39         }40         , 30)41     }42 </script>43     

 

感覺不難,重點進入函數都得清理一下定時器

js實現基礎運動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.