首页 > 解决方案 > 设置新的元素类属性值

问题描述

如何使用 javascript 将 10px 添加到 css 类属性?

例如:

var bigger = document.getElementsByClassName("size200").style.width;
bigger + 10;

标签: javascriptdom

解决方案


setTimeout(() => {

  // get width
  let width = window.getComputedStyle(document.querySelector('.some-class')).width;
  width = +width.substr(0,width.length-2);
  let newWidth = `${width+100}px`;
  
  // set style
  Array(document.getElementsByClassName('some-class').length)
    .fill()
    .map((_, index) => {
      document.getElementsByClassName('some-class')[index].style.width = newWidth;
    });
    
}, 1000)
.some-class {
  width: 200px;
  height: 200px;
  background-color: red;
  transition: all .5s;
}
<div class="some-class"></div>
<p>
wait 1s
</p>
<div class="some-class"></div>


推荐阅读