我试图在这个div中添加一个div来填充我的进度条。
<div class="progress">
</div>
我尝试使用的javascript是
function moveProgressBar(state) {
let elem = document.getElementsByClassName("progress");
let prog = state.count - 1;
let value = ((prog / state.total) * 100) + '%';
elem.innerHTML = '<div class="progress-bar progress-bar-success" role="progressbar" aria-valuemin="0" aria-valuemax="100" style=value>';
}
总体目标是让一个div和一个sub-div看起来像这样,样式值由moveProgressBar函数填充。
<div class="progress">
<div class="progress-bar progress-bar-success" role="progressbar" aria-valuemin="0" aria-valuemax="100" style=value>
</div>
</div>
答案 0 :(得分:1)
函数getElementsByClassName
返回一个元素数组,所以你要做的是document.getElementsByClassName("progress")[0]
来获取第一个元素。
答案 1 :(得分:0)
getElementsByClassName
返回所提供类的所有元素的HTML collection。您可能希望对所有此类.progress
es。
[].slice.call(elem).forEach(function (progBar) { ... } );
// [].slice.call to convert the HTML collection to a JavaScript array,
// upon which .forEach can be used.
//
// Other option would be to use a simple for loop to iterate through elem.
for(let i = 0; i < elem.length; i++) {
let progBar = elem[i];
...
}
function moveProgressBar(state) {
let elem = document.getElementsByClassName("progress");
let prog = state.count - 1;
let value = ((prog / state.total) * 100) + '%';
[].slice.call(elem).forEach(function(progressBar) {
progressBar.innerHTML = '<div class="progress-bar progress-bar-success" role="progressbar" aria-valuemin="0" aria-valuemax="100" style="width:' + value + '">';
});
}
// Sample run
var currCount = 0;
setInterval(function() {
moveProgressBar({ count: (++currCount % 42), total: 42 });
}, 250);
.progress { border: 1px #AAA solid; }
.progress-bar { height: 15px; background-color: #0E0; }
<div class="progress"></div>
注意,每次要更新.progress-bar
es值时,您可能只想更改现有的.progress
宽度,而不是创建新的.progress-bar
元素。对于您定义的每个进度条,您可能还需要单独存储当前值(aria-valuenow
)。