简体   繁体   中英

Get border width from a div with plain javascript

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 have tried with this:

window.alert( document.getElementById( "content" ).style.borderWidth );

I heard that depends of the browser maybe you can help me I'm using Firefox 18

Please try the below javascript:

alert($("#content").css("border-left-width")); //using jquery.

or

alert(getComputedStyle(document.getElementById('content'),null).getPropertyValue('border-left-width'));//without jquery.

getComputedStyle (element, pseudo)

element:The element to get a styling for

pseudo:A pseudo-selector like 'hover' or null if not needed.

Reference link: http://javascript.info/tutorial/styles-and-classes-getcomputedstyle

I might be too late but as you never marked it as answered, I thought I could give it a try.

If your problem was compatibility between browser I would create a custom method that I could use in almost every browser there is (that means going back to the very basics).

I actually dug a lot to do this. I use some of the code from jQuery because I did not want to use jQuery but still have the backwards compatibility that jQuery does.

This function solves your question and at the bottom there are some examples on how to use it.

This functions uses the "module pattern" through the immediate function that will be run as soon as the script loads creating a method that will NOT polute the global scope but extend its functionality through a function to do what you wanted.

// I give it a name but it can also be anonymous
(function preloadedFunctions(){
    // Preseted methods.
    if(window.getComputedStyle){
        window.getComputedStylePropertyValue = function(element, prop){
            var computedStyle = window.getComputedStyle(element, null);
            if(!computedStyle) return null;
            if(computedStyle.getPropertyValue) {
                return computedStyle.getPropertyValue(prop);
            } else if (computedStyle.getAttribute) {
                return computedStyle.getAttribute(prop);
            } else if(computedStyle[prop]) {
                return computedStyle[prop];
            };
        };
    }
    // jQuery JavaScript Library v1.9.0
    // http://www.minhacienda.gov.co/portal/pls/portal/PORTAL.wwsbr_imt_services.GenericView?p_docname=6240612.JS&p_type=DOC&p_viewservice=VAHWSTH&p_searchstring=
    // For IE8 or less
    else if ( document.documentElement.currentStyle ) {
        var rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
        rposition = /^(top|right|bottom|left)$/,
        core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source;
        window.getComputedStylePropertyValue = function(element, prop){
            var left, rsLeft,
            ret = element.currentStyle && element.currentStyle[ prop ],
            style = element.style;

            if ( ret == null && style && style[ prop ] ) {
                ret = style[ prop ];
            }
            if ( rnumnonpx.test( ret ) && !rposition.test( prop ) ) {
                left = style.left;
                rsLeft = element.runtimeStyle && element.runtimeStyle.left;
                if ( rsLeft ) {
                    element.runtimeStyle.left = element.currentStyle.left;
                }
                style.left = prop === "fontSize" ? "1em" : ret;
                ret = style.pixelLeft + "px";
                style.left = left;
                if ( rsLeft ) {
                    element.runtimeStyle.left = rsLeft;
                }
            }
            return ret === "" ? "auto" : ret;
        };
    };
})();

ie

1.-

var borderWidth = getComputedStylePropertyValue(document.getElementsByTagName("div")[0], "border-width");
console.log(borderWidth);

2.-

var div = document.getElementById("someID");
console.log(getComputedStylePropertyValue(div, "border-width")); 

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

let 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.

you can try this

var border =  document.getElementById("yourDiv").clientWidth - document.getElementById("yourDiv").offsetWidth; 
alert(border);

Very old question, but anyway...

This solution is , 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);

According to W3Schools , this property is supported by major browsers. Thus you shouldn't have any difficulty in using it.

However, using a JavaScript framework like jQuery would always help you not worrying about trivial issues like this.

When left & right border has same width:

function getWidth(div) {
   return (div.offsetWidth - div.clientWidth) /2
}
getWidth(document.querySelector('#content'))

Works for me

 let content = document.querySelector('#content'); // here 'borderWidth' is similar to element.style syntax let contentBorderWidth = getComputedStyle(content).borderWidth; // 1px // number, without 'px' let contentBorderWidthNumber = parseFloat(getComputedStyle(content).borderWidth); // 1 // demo content.innerHTML = contentBorderWidth +', '+ contentBorderWidthNumber; // in your case, to alert window.alert(contentBorderWidth +', '+ contentBorderWidthNumber);
 div#content { border: 1px solid skyblue; }
 <div id="content"></div>

More about getComputedStyle .

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