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

[英]How to get CSS class property in Javascript?


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

HTML -

HTML -

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

In JavaScript i want to get margin:20px

在JavaScript中我想获得保证金:20px

3 个解决方案

#1


20  

For modern browsers you can use getComputedStyle:

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

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

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

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

fiddle

小提琴

#2


1  

I've just released an npm package for this purpose exactly. You can find it here on npm or github:

我刚刚为此目的发布了一个npm包。你可以在npm或github上找到它:

npm: https://www.npmjs.com/package/stylerjs

npm:https://www.npmjs.com/package/stylerjs

github: https://github.com/tjcafferkey/stylerjs

github:https://github.com/tjcafferkey/stylerjs

you would use it like so

你会像这样使用它

var styles = styler('.class-name').get(['height', 'width']);

and styles would equal

和风格相等

{height: "50px", width: "50px}

So you could just get the values like so

所以你可以得到这样的值

var height = styles.height;

#3


0  

Using jQuery:

使用jQuery:

   $('.class').css( "backgroundColor" );

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2013/12/04/df28a40fd14eaf149d72f6872a73a7ab.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号