如何在 javascript 中获取 HTML 元素的样式值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2664045/
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
How to get an HTML element's style values in javascript?
提问by stan
I am looking for a way to retrieve the style from an element that has a style set upon it by the style tag.
我正在寻找一种方法来从具有样式标签设置的样式的元素中检索样式。
<style>
#box {width: 100px;}
</style>
In the body
在身体里
<div id="box"></div>
I'm looking for straight javascript without the use of libraries.
我正在寻找不使用库的直接 javascript。
I tried the following, but keep receiving blanks:
我尝试了以下操作,但一直收到空白:
alert (document.getElementById("box").style.width);
alert (document.getElementById("box").style.getPropertyValue("width"));
I noticed that I'm only able to use the above if I have set the style using javascript, but unable to with the style tags.
我注意到,如果我使用 javascript 设置了样式,我只能使用上述内容,但无法使用样式标签。
回答by CMS
The element.styleproperty lets you know only the CSS properties that were defined as inlinein that element (programmatically, or defined in the style attribute of the element), you should get the computed style.
该element.style属性仅让您知道在该元素中定义为内联的 CSS 属性(以编程方式,或在元素的 style 属性中定义),您应该获得计算的 style。
Is not so easy to do it in a cross-browser way, IE has its own way, through the element.currentStyleproperty, and the DOM Level 2 standardway, implemented by other browsers is through the document.defaultView.getComputedStylemethod.
跨浏览器的方式不是那么容易,IE有自己的方式,通过element.currentStyle属性,而DOM Level 2标准方式,其他浏览器实现的都是通过document.defaultView.getComputedStyle方式。
The two ways have differences, for example, the IE element.currentStyleproperty expect that you access the CCS property names composed of two or more words in camelCase(e.g. maxHeight, fontSize, backgroundColor, etc), the standard way expects the properties with the words separated with dashes (e.g. max-height, font-size, background-color, etc).
这两种方法有差异,例如,在IEelement.currentStyle属性期待您访问的两个或多个单词组成的CCS属性名驼峰(例如maxHeight,fontSize,backgroundColor等),标准的方式希望与字词的属性与破折号分开(例如max-height,font-size,background-color,等等)。
Also, the IE element.currentStylewill return all the sizes in the unit that they were specified, (e.g. 12pt, 50%, 5em), the standard way will compute the actual size in pixels always.
此外,IEelement.currentStyle将返回指定单位的所有尺寸(例如 12pt、50%、5em),标准方法将始终以像素为单位计算实际尺寸。
I made some time ago a cross-browser function that allows you to get the computed styles in a cross-browser way:
前段时间我做了一个跨浏览器的函数,可以让你以跨浏览器的方式获取计算出的样式:
function getStyle(el, styleProp) {
var value, defaultView = (el.ownerDocument || document).defaultView;
// W3C standard way:
if (defaultView && defaultView.getComputedStyle) {
// sanitize property name to css notation
// (hypen separated words eg. font-Size)
styleProp = styleProp.replace(/([A-Z])/g, "-").toLowerCase();
return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
} else if (el.currentStyle) { // IE
// sanitize property name to camelCase
styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
return letter.toUpperCase();
});
value = el.currentStyle[styleProp];
// convert other units to pixels on IE
if (/^\d+(em|pt|%|ex)?$/i.test(value)) {
return (function(value) {
var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
el.runtimeStyle.left = el.currentStyle.left;
el.style.left = value || 0;
value = el.style.pixelLeft + "px";
el.style.left = oldLeft;
el.runtimeStyle.left = oldRsLeft;
return value;
})(value);
}
return value;
}
}
The above function is not perfect for some cases, for example for colors, the standard method will return colors in the rgb(...)notation, on IE they will return them as they were defined.
上述函数在某些情况下并不完美,例如对于颜色,标准方法将返回rgb(...)表示法中的颜色,在 IE 上,它们将按照定义返回它们。
I'm currently working on an article in the subject, you can follow the changes I make to this function here.
我目前正在撰写有关该主题的文章,您可以在此处按照我对此功能所做的更改进行操作。
回答by justina_de
I believe you are now able to use Window.getComputedStyle()
我相信你现在可以使用 Window.getComputedStyle()
var style = window.getComputedStyle(element[, pseudoElt]);
Example to get width of an element:
获取元素宽度的示例:
window.getComputedStyle(document.querySelector('#mainbar')).width
回答by Jared Forsyth
In jQuery, you can do alert($("#theid").css("width")).
在jQuery 中,您可以做到alert($("#theid").css("width"))。
-- if you haven't taken a look at jQuery, I highly recommend it; it makes many simple javascript tasks effortless.
-- 如果你还没有看过 jQuery,我强烈推荐它;它使许多简单的 JavaScript 任务变得毫不费力。
Update
更新
for the record, this post is 5 years old. The web has developed, moved on, etc. There are ways to do this with Plain Old Javascript, which is better.
郑重声明,这篇文章已有 5 年历史。网络已经发展,继续前进,等等。有一些方法可以使用普通的旧 Javascript 来做到这一点,这是更好的。
回答by praveen-me
You can make function getStylesthat'll take an element and other arguments are properties that's values you want.
您可以使函数getStyles接受一个元素,而其他参数是您想要的值的属性。
const convertRestArgsIntoStylesArr = ([...args]) => {
return args.slice(1);
}
const getStyles = function () {
const args = [...arguments];
const [element] = args;
let stylesProps = [...args][1] instanceof Array ? args[1] : convertRestArgsIntoStylesArr(args);
const styles = window.getComputedStyle(element);
const stylesObj = stylesProps.reduce((acc, v) => {
acc[v] = styles.getPropertyValue(v);
return acc;
}, {});
return stylesObj;
};
Now, you can use this function like this:
现在,您可以像这样使用这个函数:
const styles = getStyles(document.body, "height", "width");
OR
或者
const styles = getStyles(document.body, ["height", "width"]);
回答by Sanjeev S
By using .css() in jquery the style tag can be accessed and modified
通过在 jquery 中使用 .css() 可以访问和修改样式标签
for example:
例如:
var color = $( this ).css( "background-color" );
$( "#result" ).html( "That div is <span style='color:" +
color + ";'>" + color + "</span>." );

