如何获取CSS类属性在Javascript? [英] How to get CSS class property in Javascript?

查看:67
本文介绍了如何获取CSS类属性在Javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.test {
    width:80px;
    height:50px;
    background-color:#808080;
    margin:20px;
}

HTML -

<div class="test">Click Here</div>

在JavaScript中我想获得 margin:20px

In JavaScript i want to get margin:20px

推荐答案

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

For modern browsers you can use 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 应单独访问。

margin is a composite style, and not reliable cross-browser. Each of -top -right, -bottom, and -left should be accessed individually.

fiddle

这篇关于如何获取CSS类属性在Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆