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

新手上路,请多包涵
.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 许可协议

阅读 457
2 个回答

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

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

margin 是复合风格,跨浏览器不可靠。 Each of -top -right , -bottom , and -left should be accessed individually.

小提琴

原文由 zzzzBov 发布,翻译遵循 CC BY-SA 3.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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题