.test {
width:80px;
height:50px;
background-color:#808080;
margin:20px;
}
HTML -
<div class="test">Click Here</div>
在JavaScript中我想得到 margin:20px
原文由 Chinmay235 发布,翻译遵循 CC BY-SA 4.0 许可协议
.test {
width:80px;
height:50px;
background-color:#808080;
margin:20px;
}
HTML -
<div class="test">Click Here</div>
在JavaScript中我想得到 margin:20px
原文由 Chinmay235 发布,翻译遵循 CC BY-SA 4.0 许可协议
接受的答案是获得计算值的最佳方式。我个人需要预先计算的值。例如,将“高度”设置为“calc()”值。我编写了以下 jQuery 函数来访问样式表中的值。此脚本处理嵌套的“媒体”和“支持”查询、CORS 错误,并应为可访问属性提供最终的级联预计算值。
$.fn.cssStyle = function() {
var sheets = document.styleSheets, ret = [];
var el = this.get(0);
var q = function(rules){
for (var r in rules) {
var rule = rules[r];
if(rule instanceof CSSMediaRule && window.matchMedia(rule.conditionText).matches){
ret.concat(q(rule.rules || rule.cssRules));
} else if(rule instanceof CSSSupportsRule){
try{
if(CSS.supports(rule.conditionText)){
ret.concat(q(rule.rules || rule.cssRules));
}
} catch (e) {
console.error(e);
}
} else if(rule instanceof CSSStyleRule){
try{
if(el.matches(rule.selectorText)){
ret.push(rule.style);
}
} catch(e){
console.error(e);
}
}
}
};
for (var i in sheets) {
try{
q(sheets[i].rules || sheets[i].cssRules);
} catch(e){
console.error(e);
}
}
return ret.pop();
};
// Your element
console.log($('body').cssStyle().height);
原文由 Bernesto 发布,翻译遵循 CC BY-SA 4.0 许可协议
13 回答13k 阅读
7 回答2.1k 阅读
3 回答1.3k 阅读✓ 已解决
2 回答1.4k 阅读✓ 已解决
6 回答1.2k 阅读✓ 已解决
2 回答914 阅读✓ 已解决
3 回答834 阅读✓ 已解决
对于现代浏览器,您可以使用
getComputedStyle
:margin
是复合风格,跨浏览器不可靠。 Each of-top
-right
,-bottom
, and-left
should be accessed individually.小提琴