如何在 Javascript 中获取 CSS 类属性

How to get CSS class property in Javascript?

本文关键字:CSS 属性 获取 Javascript      更新时间:2024-03-13
.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;