使用 JavaScript 获取 CSS 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6338217/
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
Get a CSS value with JavaScript
提问by Michael Paul
I know I can seta CSS value through JavaScript such as:
我知道我可以通过 JavaScript设置CSS 值,例如:
document.getElementById('image_1').style.top = '100px';
But, can I geta current specific style value? I've read where I can get the entire style for the element, but I don't want to have to parse the whole string if I don't have to.
但是,我可以获得当前的特定样式值吗?我已经阅读了在哪里可以获得元素的整个样式,但是如果不需要,我不想解析整个字符串。
回答by alex
You can use getComputedStyle()
.
您可以使用getComputedStyle()
.
var element = document.getElementById('image_1'),
style = window.getComputedStyle(element),
top = style.getPropertyValue('top');
回答by Amir Movahedi
The element.style property lets you know only the CSS properties that were defined as inline in that element (programmatically, or defined in the style attribute of the element), you should get the computed style.
element.style 属性让您只知道在该元素中定义为内联的 CSS 属性(以编程方式,或在元素的 style 属性中定义),您应该获得计算出的样式。
Is not so easy to do it in a cross-browser way, IE has its own way, through the element.currentStyle property, and the DOM Level 2 standard way, implemented by other browsers is through the document.defaultView.getComputedStyle method.
跨浏览器的方式不是那么容易,IE有自己的方式,通过element.currentStyle属性,而DOM Level 2标准方式,其他浏览器是通过document.defaultView.getComputedStyle方法实现的。
The two ways have differences, for example, the IE element.currentStyle property expect that you access the CSS 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). ......
两种方式有区别,例如IE的element.currentStyle属性期望你访问由camelCase中的两个或多个单词组成的CSS属性名称(例如maxHeight、fontSize、backgroundColor等),标准方式期望具有用破折号分隔的单词(例如最大高度、字体大小、背景颜色等)。......
function getStyle(el, styleProp) {
var value, defaultView = (el.ownerDocument || document).defaultView;
// W3C standard way:
if (defaultView && defaultView.getComputedStyle) {
// sanitize property name to css notation
// (hyphen 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;
}
}
回答by user843938
Use the following. It helped me.
使用以下内容。它帮助了我。
document.getElementById('image_1').offsetTop
See also Get Styles.
另请参阅获取样式。
回答by karolf
Cross-browser solution to checking CSS values without DOM manipulation:
无需 DOM 操作即可检查 CSS 值的跨浏览器解决方案:
function get_style_rule_value(selector, style)
{
for (var i = 0; i < document.styleSheets.length; i++)
{
var mysheet = document.styleSheets[i];
var myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;
for (var j = 0; j < myrules.length; j++)
{
if (myrules[j].selectorText && myrules[j].selectorText.toLowerCase() === selector)
{
return myrules[j].style[style];
}
}
}
};
Usage:
用法:
get_style_rule_value('.chart-color', 'backgroundColor')
Sanitized version (forces selector input to lowercase, and allows for use case without leading ".")
消毒版本(强制选择器输入小写,并允许用例不带前导“.”)
function get_style_rule_value(selector, style)
{
var selector_compare=selector.toLowerCase();
var selector_compare2= selector_compare.substr(0,1)==='.' ? selector_compare.substr(1) : '.'+selector_compare;
for (var i = 0; i < document.styleSheets.length; i++)
{
var mysheet = document.styleSheets[i];
var myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;
for (var j = 0; j < myrules.length; j++)
{
if (myrules[j].selectorText)
{
var check = myrules[j].selectorText.toLowerCase();
switch (check)
{
case selector_compare :
case selector_compare2 : return myrules[j].style[style];
}
}
}
}
}
回答by adotout
If you set it programmatically you can just call it like a variable (i.e. document.getElementById('image_1').style.top
). Otherwise, you can always use jQuery:
如果您以编程方式设置它,您可以像变量一样调用它(即document.getElementById('image_1').style.top
)。否则,您始终可以使用 jQuery:
<html>
<body>
<div id="test" style="height: 100px;">Test</div>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
alert($("#test").css("height"));
</script>
</body>
</html>
回答by RobG
回答by Nisharg Shah
In 2020
2020年
checkbefore use
使用前检查
You can use computedStyleMap()
您可以使用计算样式映射()
The answer is valid but sometimes you need to check what unit it returns, you can get that without any slice()
or substring()
string.
答案是有效的,但有时您需要检查它返回的单位,您可以在没有任何单位slice()
或substring()
字符串的情况下获得该单位。
var element = document.querySelector('.js-header-rep');
element.computedStyleMap().get('padding-left');
var element = document.querySelector('.jsCSS');
var con = element.computedStyleMap().get('padding-left');
console.log(con);
.jsCSS {
width: 10rem;
height: 10rem;
background-color: skyblue;
padding-left: 10px;
}
<div class="jsCSS"></div>
回答by BryanH
As a matter of safety, you may wish to check that the element exists before you attempt to read from it. If it doesn't exist, your code will throw an exception, which will stop execution on the rest of your JavaScript and potentially display an error message to the user -- not good. You want to be able to fail gracefully.
出于安全考虑,您可能希望在尝试读取元素之前检查该元素是否存在。如果它不存在,您的代码将抛出一个异常,这将停止在您的 JavaScript 的其余部分上执行,并可能向用户显示一条错误消息 - 不好。你希望能够优雅地失败。
var height, width, top, margin, item;
item = document.getElementById( "image_1" );
if( item ) {
height = item.style.height;
width = item.style.width;
top = item.style.top;
margin = item.style.margin;
} else {
// Fail gracefully here
}
回答by jcdufourd
The cross-browser solution without DOM manipulation given above does not work because it gives the first matching rule, not the last. The last matching rule is the one which applies. Here is a working version:
上面给出的没有 DOM 操作的跨浏览器解决方案不起作用,因为它给出了第一个匹配规则,而不是最后一个。最后一个匹配规则是适用的规则。这是一个工作版本:
function getStyleRuleValue(style, selector) {
let value = null;
for (let i = 0; i < document.styleSheets.length; i++) {
const mysheet = document.styleSheets[i];
const myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;
for (let j = 0; j < myrules.length; j++) {
if (myrules[j].selectorText &&
myrules[j].selectorText.toLowerCase() === selector) {
value = myrules[j].style[style];
}
}
}
return value;
}
However, this simple search will not work in case of complex selectors.
但是,这种简单的搜索在复杂选择器的情况下不起作用。