js多個物體運動的問題1

來源:互聯網
上載者:User

標籤:style   blog   http   width   art   io   

問題2

http://www.cnblogs.com/huaci/p/3854304.html

 

用js寫一個物體的運動很簡單。如果一個頁面有多個物體在運動,它會不會出問題呢?

ok,我們來看一個樣本

讓多個div變寬

現象:onmouseover時,div寬度變寬;onmouseout時,div恢複原大小

 

html部分

<div id="div1"></div><div id="div2"></div><div id="div3"></div><style>div { width:100px; height:30px; margin:10px; background:green;}</style>

 

js部分

<script>window.onload = function(){var aDiv = document.getElementsByTagName("div");for(var i=0; i<aDiv.length; i++){aDiv[i].onmouseover = function(){startMove(this,400);}aDiv[i].onmouseout = function(){startMove(this,100);}}}var timer = null;function startMove(obj, iTarget){clearInterval(timer);timer = setInterval(function(){var speed = (iTarget - obj.offsetWidth)/6;speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);if(obj.offsetWidth == iTarget){clearInterval(timer);} else {obj.style.width = obj.offsetWidth + speed + "px";}},30);}</script>

  

運行後,

問題:當滑鼠在幾個div之間來回切換操作時,發現之間的div停住了,收不回去了

原因:分析上面代碼,原來是進入一個新的div操作時,把之前的所有定時器都給關了

一句話:整個程式就只有一個定時器

 

解決:為每個運動對象,都定義一個定時器

只開啟和關閉當前操作的這個運動對象的定時器

 

現在給出修改後的完整代碼啊

 

完整樣本:

<script>window.onload = function(){var aDiv = document.getElementsByTagName("div");for(var i=0; i<aDiv.length; i++){aDiv[i].timer = null;      aDiv[i].onmouseover = function(){startMove(this,400);}aDiv[i].onmouseout = function(){startMove(this,100);}}}function startMove(obj, iTarget){clearInterval(obj.timer);obj.timer = setInterval(function(){var speed = (iTarget - obj.offsetWidth)/6;speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);if(obj.offsetWidth == iTarget){clearInterval(obj.timer);} else {obj.style.width = obj.offsetWidth + speed + "px";}},30);}</script>

  

下一節,問題2

http://www.cnblogs.com/huaci/p/3854304.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.