如何在Javascript中获取CSS类属性?

Chi*_*235 28 html javascript css

.test {
    width:80px;
    height:50px;
    background-color:#808080;
    margin:20px;
}
Run Code Online (Sandbox Code Playgroud)

HTML -

<div class="test">Click Here</div>
Run Code Online (Sandbox Code Playgroud)

在JavaScript中,我希望得到 margin:20px

zzz*_*Bov 26

对于现代浏览器,您可以使用getComputedStyle:

var elem,
    style;
elem = document.querySelector('.test');
style = getComputedStyle(elem);
style.marginTop; //`20px`
style.marginRight; //`20px`
style.marginBottom; //`20px`
style.marginLeft; //`20px`
Run Code Online (Sandbox Code Playgroud)

margin是一种复合风格,而不是可靠的跨浏览器.每个的-top -right,-bottom以及-left应单独访问.

小提琴

  • 包括jQuery并使用它更简单和更好$('.test').css("margin"); (4认同)

Ber*_*sto 5

接受的答案是获得计算值的最佳方法。我个人需要预先计算的值。例如,将“高度”设置为“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);
Run Code Online (Sandbox Code Playgroud)