如何使用 JavaScript 获取元素的填充值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5227909/
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-08-23 16:15:59  来源:igfitidea点击:

How to get an element's padding value using JavaScript?

javascripthtmlpadding

提问by R. Dewi

I have a textareain my HTML. I need to get the padding numerical value in pixels as either integer or float. How can I get it using JavaScript? I am not using jQuery, so I'm looking for pure JavaScript solutions.

textarea我的 HTML 中有一个。我需要以像素为单位获取填充数值作为整数或浮点数。如何使用 JavaScript 获取它?我没有使用 jQuery,所以我在寻找纯 JavaScript 解决方案。

回答by ?ime Vidas

This will return the padding-leftvalue:

这将返回padding-left值:

window.getComputedStyle(txt, null).getPropertyValue('padding-left')

where txtis the reference to your TEXTAREA element.

哪里txt是对您的 TEXTAREA 元素的引用。

The above works in all modern browsers and in IE9. However, it does not work in IE8 and below.

以上适用于所有现代浏览器和 IE9。但是,它在 IE8 及以下版本中不起作用。

Live demo:http://jsfiddle.net/simevidas/yp6XX/

现场演示:http : //jsfiddle.net/simevidas/yp6XX/

Further reading: https://developer.mozilla.org/en/DOM:window.getComputedStyle

进一步阅读:https: //developer.mozilla.org/en/DOM: window.getComputedStyle



Btw, just for comparison, this is how you get the same job done using jQuery:

顺便说一句,只是为了比较,这就是您使用 jQuery 完成相同工作的方式:

$(txt).css('padding-left')

The above does work in IE6-8.

以上在 IE6-8 中确实有效。

回答by Chuck Callebs

After a search, I found this resourceto do what you're looking to do.

搜索后,我发现这个资源可以做你想做的事情。

They want you to add a javascript function:

他们希望你添加一个 javascript 函数:

function getStyle(oElm, strCssRule){
    var strValue = "";
    if(document.defaultView && document.defaultView.getComputedStyle){
        strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
    }
    else if(oElm.currentStyle){
        strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
            return p1.toUpperCase();
        });
        strValue = oElm.currentStyle[strCssRule];
    }
    return strValue;
}

And then call the function like this to obtain the particular style:

然后像这样调用函数来获取特定的样式:

getStyle(document.getElementById("container"), "padding-right");

Where "container" is the id of the element and "font-size" is the property name. If you can guarantee that all the CSS on the element will be inline then this solution would be cleaner:

其中“container”是元素的id,“font-size”是属性名称。如果你能保证元素上的所有 CSS 都是内联的,那么这个解决方案会更清晰:

document.getElementById("container").style.paddingRight;