Offset bug in Javascript motion-line-by-line code analysis allows you to easily understand the principle of motion
Let's take a look at how this bug was generated. <Style type = "text/css"> # div1 {width: 200px; height: 200px; background: red ;} </style> <body> <div id = "div1"> </div> </body> The following Javascript code is used for testing to narrow the div. <Script type = "text/javascript"> setInterval (function () {var oDiv = document. getElementById ("div1"); oDiv. style. width = oDiv. offsetWidth-1 + 'px ';}, 30); </script> Javascript code is very simple, run it without any problem, as expected div is slowly becoming smaller. So how does this offset bug come from? Next, let's move the style to make it happen... Add a style border: 1px solid # CCCCFF to div1; <style type = "text/css"> # div1 {width: 200px; height: 200px; background: red; border: 1px solid # CCCCFF;} </style> the code is running, and the div is gradually increased to the right... Image BUG .... It is clear why this problem occurs when the value is reduced by 1. Let's look at the characteristics of offset: for example, div width: 200px border 1px. In fact, the offsetWidth obtained is 202px. So, let's say that when the movement is just starting, the actually div width is 200px, so offsetWidth is 202. In this case, oDiv. style. width = oDiv. offsetWidth-1 + 'px '; this sentence is equal to oDiv. style. width = 202-1 = 201px; then, assign the value to width. When this sentence is executed again, the div width is 201px. In this way, 1px is added each time, but the size increases gradually. This is the offset bug. How can this problem be solved? You don't need to use offsetWidth. We use width !! Write a function to directly obtain the width in the css style to obtain the style that is not included in the line: function getStyle (obj, name) {if (obj. currentStyle) {return obj. currentStyle [name];} else {return getComputedStyle (obj, null) [name] ;}} then we are modifying the original code: <script type = "text/javascript"> setInterval (function () {var oDiv = document. getElementById ("div1"); oDiv. style. width = parseInt (getStyle (oDiv, 'width')-1 + 'px' ;}, 30); function getStyle (obj, name) {if (obj. currentStyle) {return obj. currentStyle [name];} else {return getComputedStyle (obj, null) [name] ;}</script>