如何在 Javascript 中获取 CSS 类属性
How to get CSS class property in Javascript?
.test {
width:80px;
height:50px;
background-color:#808080;
margin:20px;
}
.HTML-
<div class="test">Click Here</div>
在 JavaScript 中,我想得到margin:20px
对于现代浏览器,您可以使用getComputedStyle
:
var elem,
style;
elem = document.querySelector('.test');
style = getComputedStyle(elem);
style.marginTop; //`20px`
style.marginRight; //`20px`
style.marginBottom; //`20px`
style.marginLeft; //`20px`
margin
是一种复合样式,而不是可靠的跨浏览器。-top
-right
、-bottom
和-left
中的每一个都应该单独访问。
小提琴
接受的
答案是获取计算值的最佳方式。我个人需要预先计算的值。例如,假设"高度"设置为"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);
使用 jQuery:
$('.class').css( "backgroundColor" );
另一种方法(仍处于实验阶段(可以是 computedStyleMap:
const computedStyleMap = document.getElementById('my-id').computedStyleMap();
computedStyleMap.get('overflow-x'); // {value: 'scroll'}
computedStyleMap.has('padding-right'); // false
computedStyleMap.entries(); // Iterator {}
我刚刚为此目的发布了一个 npm 包。你可以在npm或github上找到它:
NPM: https://www.npmjs.com/package/stylerjs
GitHub:https://github.com/tjcafferkey/stylerjs
你会这样使用它
var styles = styler('.class-name').get(['height', 'width']);
和样式将相等
{height: "50px", width: "50px"}
所以你可以得到这样的值
var height = styles.height;
相关文章:
- 谷歌图表-如何更改整个表的css属性
- 将css属性替换为变量
- 使用Jquery/Javascript替换CSS属性
- 如何使用JavaScript查找未定义的CSS属性的值
- 在jquerymobile中设置按钮css属性的动画
- JavaScript无法提取引号css属性
- 使用AngularJS动态更改css属性
- 使用javascript获取具有特定CSS属性的所有元素
- 将css属性添加到对象的集合中
- 取消img的css属性宽度和高度(不能使用“auto”)
- CSS属性更改侦听器
- 如何更改与Backbone集合中的模型相关联的几个元素的css属性
- 如何使用java脚本或jQuery基于相同的特定css属性对元素进行分组
- 如何在不链接/jquery的情况下使用方法应用css属性数组
- 在 javascript css 属性中使用变量
- 在jQuery中链接时CSS属性不起作用
- jQuery检查CSS宽度是否大于0,然后添加CSS属性
- 使用循环增加css属性值
- 更改类所选空输入的CSS属性
- 无法查找元素'手动加载CSS文件时的CSS属性