Get border width from a div with plain javascript

前端 未结 6 2081
日久生厌
日久生厌 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:31

    Very old question, but anyway...

    This solution is plain JavaScript, and should work in older browsers too. It measures the size of the element, with, and without borders.

    The following example should work correctly if the borders around the element are all the same size. If not, the procedure doesn't change much, you just have to set the borders equal to zero, one by one.

    var ele=document.getElementById("content");
    // measures the element width, WITH borders
    var w=ele.offsetWidth;
    var cssBackup=ele.style.cssText;
    // sets the borders to zero
    ele.style.border="0px";
    // computes the border size
    var bord=(w-ele.offsetWidth)/2;
    // resets the css
    ele.style.cssText=cssBackup;
    alert(bord);
    

提交回复
热议问题