bug solution for Offset in Javascript campaign

  • 2020-05-09 18:08:11
  • OfStack

So let's see how this bug comes about.


<style type="text/css">
            #div1 {
                width: 200px;
                height: 200px;
                background: red;
               
            }
        </style>


<body>
        <div id="div1">
           
        </div>
    </body>

Here is the Javascript code for testing, with the goal of narrowing down div.


<script type="text/javascript">
            setInterval(function(){
                var oDiv=document.getElementById("div1");
               
                oDiv.style.width=oDiv.offsetWidth-1+'px';
               
            },30);
        </script>

The Javascript code is very simple, running 1 without any problems, the desired div is getting smaller and smaller.

So where does this offset bug come from?

Now let's move the style and something amazing will happen...

Let's style div1 border: 1px solid #CCCCFF;


<style type="text/css">
            #div1 {
                width: 200px;
                height: 200px;
                background: red;
                border: 1px solid #CCCCFF;
            }
        </style>

While running the code, I noticed that div was growing to the right... image BUG... Obviously minus 1 is why this is happening.

Let's think about the features of offset:

Example: div width: 200px   border 1px  . He actually gets offsetWidth is 202px.

So, let's get back to the fact that at the beginning of the campaign, the width of div is actually 200px   and the width of offsetWidth is 202

At this time oDiv.style.width = oDiv.offsetWidth-1 +'px'; width=202-1=201px; oDiv. style. width=202-1=201px; And then assign width

When this sentence is repeated the width of div is 201px; In this case, it will increase by 1px each time, but it will gradually increase. This is bug for offset.

How to solve this problem?

You don't have to use the offsetWidth. We use width!! Just write a function to get width directly from the css style

Get styles that are not in between lines:


function getStyle(obj, name) {
                if (obj.currentStyle) {
                    return obj.currentStyle[name];
                } else {
                    return getComputedStyle(obj, null)[name];
                }
            }

So let's modify 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>

 
Then the program will run without any problems.


Related articles: