简体   繁体   中英

Better way to get the border width in javascript?

I use this :

var playGard =document.getElementsByClassName("playGard")[0];

var borderW= getComputedStyle(playGard,null).getPropertyValue('border-left-width').substr(0,2);

I get the value "10".

There is a better shorter way in javascript?

(Get the value as a number)

Obviously, substr(0, 2) is not a good idea, because it won't work if the width is less than 10, or greater than 100.

Instead, just remove the "px" string (if it's there; it might not be if the value is 0):

+val.replace('px', '')

The leading + is to convert this to a number.

But why?

The more interesting question is why you're trying to get the border width. What were you planning to do with it? Using getComputedStyle is a bit of an anti-pattern. It often indicates that you're trying to maintain application state within CSS, which is never a good idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM