【问题标题】:Building a progress bar with pure JavaScript [closed]使用纯 JavaScript 构建进度条 [关闭]
【发布时间】:2020-05-25 04:41:41
【问题描述】:

我正在尝试构建一个普通的 JavaScript 进度条。

<div id="progress-bar" style="width:10%;">

样式在 10 秒内从 width:0%width:100%

我正在寻找纯 JavaScript 解决方案。

这是我的小提琴的链接 - http://fiddle.jshell.net/5j6gf/

【问题讨论】:

  • @WhiteRabbit:感谢您想在这里编辑问题。但是,您在问题中添加了五个新错误,所以我想知道您是否可以通过其他方式做出最好的贡献。社区非常希望进行编辑的贡献者精通英语技术写作。

标签: javascript html css


【解决方案1】:

在 jsfiddle 中:http://fiddle.jshell.net/5j6gf/1/

如何在javascript中制作动画的答案来自这里:https://stackoverflow.com/a/11213374/1524085

function animate(elem,style,unit,from,to,time) {
    if( !elem) return;
    var start = new Date().getTime(),
        timer = setInterval(function() {
            var step = Math.min(1,(new Date().getTime()-start)/time);
            elem.style[style] = (from+step*(to-from))+unit;
            if( step == 1) clearInterval(timer);
        },25);
    elem.style[style] = from+unit;
}

animate(
    document.getElementById('progress-bar'),
    "width","%",0,100,1000
);

【讨论】:

  • 这是个好主意,伙计
【解决方案2】:

您应该考虑改用 CSS 过渡:

#progress-bar {
  width: 0%;
  -moz-transition: width 10s linear;
  -webkit-transition: width 10s linear;
  transition: width 10s linear;
}

然后

document.getElementById("progress-bar").style.width = "100%";

【讨论】:

    【解决方案3】:

    在 jQuery 中可以做的任何事情都可以在纯 JavaScript 中实现。 要么解决你的问题,要么找到它是如何在 jQuery 中完成的,然后尝试用 JS 重写它。

    您可以使用 setTimeout 或 setInterval 来及时增加宽度百分比。您还需要通过将宽度增加一个像素来使每次增加尽可能平滑,直到达到所需的宽度。

    有数百万种方法可以做到这一点,找到适合您的方法。

    【讨论】:

      猜你喜欢
      • 2021-12-10
      • 2014-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-02
      • 1970-01-01
      相关资源
      最近更新 更多