Javascript multi-object motion-line-by-line analysis code helps you easily understand the motion Principle
Let's take a look at the previous motion code to see if multi-object motion is supported. <Style type = "text/css"> div {width: 100px; height: 50px; background: red; margin: 10px ;} </style> <body> <div> </body> The following Javascript code is used: <script type = "text/javascript"> 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 = f Unction () {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> when the mouse moves to the first div, it runs normally. However, if you move to the second or third div, a bug occurs. Why is image? The figure shows that the motion is not completed. In fact, the whole program has a timer. For example, when the first div starts to move, the second div moves its mouse into the previous timer and is killed, that's where it is. So the biggest problem is that the entire program has only one timer. So how can we solve this problem? Solution: in fact, it is very simple to add a timer as the attribute of an object. Every object has a timer. When the timer is closed, the timer on the object is closed, when the timer is enabled on the object, they can run completely without mutual interference. Check the modified Javascript code: <script type = "text/javascript"> window. onload = function () {var aDiv = document. getElementsByTagName ('div '); for (var I = 0; I <aDiv. length; I ++) {aDiv [I]. timer = null; // Save the timer as an object property aDiv [I]. onmouseover = function () {startMove (this, 400) ;}; aDiv [I]. onmouseout = function () {startMove (this, 100) ;}} function startMove (obj, iTarget) {clearInterval (obj. timer); obj. ti Mer = 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>. In this way, the program has no problems and supports the movement of multiple objects.