Get border width from a div with plain javascript

前端 未结 6 1936
日久生厌
日久生厌 2020-12-30 23:44

I got this style applied to a div

div#content {
border: 1px solid skyblue;  
}

and i want to be able to alert the width of the border, I ha

6条回答
  •  借酒劲吻你
    2020-12-31 00:37

    If somebody is still looking, this seems to be easiest way to do it with plain JS.

    var border = 
    +getComputedStyle((document.getElementById("idOfYourElement")))
    .borderTopWidth.slice(0, -2)
    

    Explanation below:
    document.getElementById("idOfYourElement") - Return our HTML element.

    getComputedStyle - Return css attributes of chosen element as object.

    .borderTopWidth - Corresponding attribute from getComputedStyle object (return array like this: ("10px")).

    .slice(0, -2) - Cut the last 2 characters from our array so we get rid of px at the end.

    And + at the start - Parse rest of our string, that contains number we want, to the integer.

提交回复
热议问题