javascript 使用普通的javascript从div获取边框宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14681002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:18:34  来源:igfitidea点击:

Get border width from a div with plain javascript

javascripthtmlcss

提问by Alejandro

I got this style applied to a div

我将此样式应用于 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

我听说这取决于浏览器也许你可以帮助我我正在使用 Firefox 18

回答by Sankar V

Please try the below javascript:

请尝试以下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)

getComputedStyle(元素,伪)

element:The element to get a styling for

element: 要为其设置样式的元素

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

伪:伪选择器,如“悬停”或不需要时为空。

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

参考链接:http: //javascript.info/tutorial/styles-and-classes-getcomputedstyle

回答by pgarciacamou

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.

我实际上挖了很多东西来做到这一点。我使用了 jQuery 的一些代码,因为我不想使用 jQuery 但仍然具有 jQuery 的向后兼容性。

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.

IE

1.-

1.-

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

2.-

2.-

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

回答by Gryso

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

如果有人还在寻找,这似乎是使用普通 JS 最简单的方法。

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

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

下面的解释:
document.getElementById("idOfYourElement")- 返回我们的 HTML 元素。

getComputedStyle- Return css attributes of chosen element as object.

getComputedStyle- 将所选元素的 css 属性作为对象返回。

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

.borderTopWidth- 来自getComputedStyle对象的相应属性(像这样返回数组:)("10px")

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

.slice(0, -2)- 从我们的数组中删除最后 2 个字符,以便我们在最后去掉 px。

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

+在开始-解析休息我们的字符串,其中包含我们要数到整数的。

回答by Lux

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

这个解决方案是纯 JavaScript,也应该在旧浏览器中工作。它可以测量元件的尺寸,国界。

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

回答by Shailesh

you can try this

你可以试试这个

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

回答by Saeed Neamati

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

根据W3Schools 的说法,主要浏览器都支持此属性。因此,您在使用它时应该没有任何困难。

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

但是,使用像 jQuery 这样的 JavaScript 框架总是可以帮助您不必担心这样的小问题。