Get border width from a div with plain javascript

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

    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;
            };
        };
    })();
    

    i.e.

    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")); 
    
    0 讨论(0)
  • 2020-12-31 00:29

    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.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-31 00:45

    you can try this

    var border =  document.getElementById("yourDiv").clientWidth - document.getElementById("yourDiv").offsetWidth; 
    alert(border);
    
    0 讨论(0)
  • 2020-12-31 00:47

    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

    0 讨论(0)
提交回复
热议问题