设置新元素类的属性值

时间:2018-12-10 20:18:10

标签: javascript dom

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

例如:

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

2 个答案:

答案 0 :(得分:1)

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>

答案 1 :(得分:1)

要获得预期结果,请使用以下选项

let width = document.getElementsByClassName("size200")[0].clientWidth + 10;
document.getElementsByClassName("size200")[0].style.width = width + 'px'

codepen-https://codepen.io/nagasai/pen/roazyL

let width = document.getElementsByClassName("size200")[0].clientWidth + 10;
document.getElementsByClassName("size200")[0].style.width = width + 'px'
.size200{
  width: 200px;
  border: 1px solid black;
  height: 20px
}

.size100{
  width: 200px;
  border: 1px solid black;
  height: 20px
}
<div class="size200">
  
</div>

<div class="size200">
  
</div>

<div class="size100">
  
</div>

以上解决方案将仅更改第一类,以应用于具有相同类的每个元素

for(var i = 0; i < document.getElementsByClassName("size200").length; i++){
    let width = document.getElementsByClassName("size200")[i].clientWidth + 10;
    document.getElementsByClassName("size200")[i].style.width = width + 'px'
}

codepen-https://codepen.io/nagasai/pen/vvEJRz