Solve the div width problem caused by the border attribute using js

Source: Internet
Author: User

Let's look at a routine.
Copy codeThe Code is as follows:
<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 '; // theoretically the width should be reduced, but the actual growth, the reason in the style sheet border attribute, remove to solve
}, 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>

Pay attention to the notes. Why does this happen? It is actually caused by border, because OK. style. width specifies the div width, while offsetwidth refers to the actual width, including the border width. Therefore, the width value obtained from the formula on the right is actually one pixel larger than that on the left. The solution is to subtract three pixels each time to actually subtract one pixel. Or use parseInt (div. style. width) On the right side, but modify the div as follows:
Copy codeThe Code is as follows:
<Div id = "OK" style = "width: 200px:> </div>

Ultimate Solution: Use currentstyle or getcomputedstyle to obtain attributes.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.