Let's first look at how this bug occurs.
The code copy is as follows:
<style type="text/css">
#div1 {
width: 200px;
height: 200px;
background: red;
}
</style>
The code copy is as follows:
<body>
<div id="div1">
</div>
</body>
The following is the Javascript code used to test, with the purpose of making the div gradually narrow.
The code copy is as follows:
<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, there is no problem running it, and the div that you want is gradually getting smaller.
So how did this offset bug come about?
Now, something magical will happen if we move the style. . .
We add a style border to div1: 1px solid #CCCCFF;
The code copy is as follows:
<style type="text/css">
#div1 {
width: 200px;
height: 200px;
background: red;
border: 1px solid #CCCCFF;
}
</style>
At this time, when running the code, I found that the div was gradually increasing to the right. . . image bug appeared. . . . It is obviously minus 1, why does this happen?
Let's think about the characteristics of offset:
Example: div width: 200px border 1px. In fact, the offsetWidth he gets is 202px.
So, let's talk about it again, when the movement first started, the width of the div was actually 200px, and the offsetWidth was 202
At this time oDiv.style.width=oDiv.offsetWidth-1+'px'; This sentence is equal to oDiv.style.width=202-1=201px; and then assign the value to width
When this sentence is executed again, the width of the div is 201px; in this case, 1px will be added each time, and it will gradually become larger. This is the bug of offset.
How to solve this problem?
Actually, you don't need this offsetWidth. We use width! ! Write a function to directly get width in the css style
Get styles that are not in between lines:
The code copy is as follows:
function getStyle(obj, name) {
if (obj.currentStyle) {
return obj.currentStyle[name];
} else {
return getComputedStyle(obj, null)[name];
}
}
Then we modify the original code:
The code copy is as follows:
<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>
This way there will be no problems with the program running.