Use js to solve the div width problem caused by the border attribute

  • 2020-03-29 23:59:57
  • OfStack

Now let's look at a routine
 
<script type="text/javascript"> 
var timer 
function stopMove(){ 
clearInterval(timer) 
} 
function startMove(){ 
var div=document.getElementById('ok') 
clearInterval(timer) 
timer=setInterval(function(){ 
ok.style.width=ok.offsetWidth-1+'px' ;//In theory it should be decreasing in width, but in practice it is increasing. The reason is in the border attribute in the style sheet, which can be removed
},20) 
} 
</script> 
<style type="text/css"> 
* {margin: 0;padding:0} 
body {font-size: 14px;line-height: 24px;margin: 0px;padding: 0px;} 
#ok{width:800px;height: 200px;background-color:darkgreen;border: 1px red solid; } 
</style> 
</head> 
<body> 
<div id="ok"></div> 

Look at the comments. Why is this happening? Ok. Style.width specifies the width of div, while offsetwidth refers to the actual width, including the border width. So this right hand side is actually going to be one pixel wider than the left hand side, and the solution is to subtract 3 pixels at a time to actually subtract 1 pixel. Or use parseInt(div.style.width) on the right, but modify the div as follows:
 
<div id="ok" style="width:200px:></div> 

The ultimate solution: get the property using currentstyle or getcomputedstyle.

Related articles: