Get a CSS value with JavaScript

前端 未结 9 1443
温柔的废话
温柔的废话 2020-11-21 07:55

I know I can set a CSS value through JavaScript such as:

document.getElementById(\'image_1\').style.top = \'100px\';

But, can I

9条回答
  •  情话喂你
    2020-11-21 07:57

    In 2020

    check before use

    You can use computedStyleMap()

    The answer is valid but sometimes you need to check what unit it returns, you can get that without any slice() or substring() string.

    var element = document.querySelector('.js-header-rep');
    element.computedStyleMap().get('padding-left');
    

    var element = document.querySelector('.jsCSS');
    var con = element.computedStyleMap().get('padding-left');
    console.log(con);
    .jsCSS {
      width: 10rem;
      height: 10rem;
      background-color: skyblue;
      padding-left: 10px;
    }

提交回复
热议问题