【问题标题】:Generate one percent width every second每秒生成百分之一的宽度
【发布时间】:2019-12-20 21:36:53
【问题描述】:

好的,我正在尝试每隔一秒添加一个 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);
}

【问题讨论】:

    标签: javascript loops settimeout


    【解决方案1】:

    而不是循环,使用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%;
    }
    &lt;div id="position"&gt;&lt;/div&gt;

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

    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>

    【讨论】:

    • 我的回答有什么问题?
    • 用更多的方法做某事没有错@MohammadAbedi
    【解决方案2】:

    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();
    &lt;div id="position"&gt;&lt;/div&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多