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(){ 
function startMove(){ 
var div=document.getElementById('ok') 
timer=setInterval(function(){'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
<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; } 
<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( 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: