How to get CSS class property in Javascript?

前端 未结 4 1960
挽巷
挽巷 2020-12-14 06:41
.test {
    width:80px;
    height:50px;
    background-color:#808080;
    margin:20px;
}

HTML -

Click H
4条回答
  •  独厮守ぢ
    2020-12-14 07:00

    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 is a composite style, and not reliable cross-browser. Each of -top -right, -bottom, and -left should be accessed individually.

    fiddle

提交回复
热议问题