使用javascript更改进度条的宽度

时间:2016-02-22 11:15:10

标签: javascript html

我尝试用java脚本更改bootstrap进度条的宽度但是没有工作。我在head部分编写了这段代码。请指教。

document.getElementsByClassName("progress-bar").setAttribute("style", "width:50%");
document.getElementsByClassName("progress-bar").style.width = "width:50%";

Html:

<div class="progress">
    <div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100">
    </div>
</div>

2 个答案:

答案 0 :(得分:2)

getElementsByClassName() 会返回一个节点列表,您应该指定要更改的节点的索引:

document.getElementsByClassName("progress-bar")[0].setAttribute("style", "width:50%");
document.getElementsByClassName("progress-bar")[0].style.width = "50%";

希望这有帮助。

答案 1 :(得分:2)

我建议您使用document.querySelector - 它会返回单个元素
All major browsers support it

这是不正确的

document.getElementsByClassName("progress-bar").style.width = "width:50%";
//must be
document.getElementsByClassName("progress-bar").style.width = "50%";

下面的结帐演示

var percent = 10;
document.querySelector(".progress-bar").style.width = percent + "%";
function increase(){
  percent = percent > 90 ? 10 : percent + 10;
  document.querySelector(".progress-bar").style.width = percent + "%";
}
.progress{
  background: red;
  padding: 3px;
}
.progress-bar{
  background: blue;
  height: 10px;
}
<div class="progress">
    <div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100">
    </div>
</div>
<hr />
<button onclick="increase()">increase</button>