每秒产生百分之一的宽度

Generate one percent width every second

好的,我正在尝试每隔一秒添加一个 1% 的宽度和背景颜色,但它出现在一个块中...

有人可以帮助我吗?

谢谢大家

这是我的代码:

setTimeout(function() {
  var percentage = 1;
  for (var i = 0; i < 10; i++) {
    var blabla = i + percentage
    console.log(blabla)
    document.getElementById("position").style.width = blabla + "%";
    document.getElementById("position").style.backgroundColor = "blue";
    document.getElementById("position").style.height = "20px";
  }
}, 1000);
}

document.getElementById("position").style.backgroundColor = "blue";
var i = 0;
function loop(){ 
  i++;
  document.getElementById("position").style.width = i+"%";
  document.getElementById("position").innerHTML = i+"%";
  if(i<10) {
    setTimeout(function() {
      loop();
    }, 1000);
  }
}
loop();
<div id="position"></div>

而不是循环,使用 setInterval

const increment = 1;
const tick = 1000;
let percent = 0;

const timer = setInterval(() => {
  const div = document.querySelector('#position');
  percent += increment;
  div.style.width = `${percent}%`;
  if ( percent >= 100 ) clearInterval(timer);
}, tick);
#position {
  background-color: blue;
  height: 20px;
  width: 1%;
}
<div id="position"></div>

也许让我们对几个进度条执行此操作。

const timers = [];

const doTimer = (id, { tick = 1000, increment = 1 } = {}) => {
  let percent = 0;
  timers[id] = setInterval(() => {
    const div = document.querySelector(`#${id}`);
    percent += increment;
    div.style.width = `${percent}%`;
    div.innerHTML = `${percent}%`;
    if ( percent >= 100 ) clearInterval(timers[id]);
  }, tick);  
};

doTimer('position');
doTimer('data', { tick: 500 });
doTimer('another', { increment: 5 });
#position, #data, #another {
  background-color: blue;
  height: 20px;
  width: 1%;
}

#data {
  background-color: red;
}

#another {
  background-color: yellow;
}
<div id="position"></div>
<div id="data"></div>
<div id="another"></div>