从我的代码中可以看到,进度条不会增加偶数个单位.我需要容器保持响应,但进度条要增加偶数个单位.

function increaseProgress() {
  var progressBar = document.querySelector(".progress-bar")
  var currWidth = progressBar.clientWidth;
  progressBar.style.width = currWidth + 10 + "%";
}
.progress-container {
  width: 100%;
  height: 20px;
  outline: solid 2px #ccc;
  border-radius: 20px;
}

.progress-bar {
  width: 0;
  height: inherit;
  background: blue;
  border-radius: 20px;
}
<div class="progress-container">
  <div class="progress-bar"></div>
</div>
<button onclick="increaseProgress()">Click to increase</button>

推荐答案

@evolutionxbox在 comments 中提出了一个很好的建议.它比您正在采用的手动方法灵活得多.

但是,如果您仍在寻找当前代码的修复程序,那么以下是一个:

首先,您需要了解容器的总宽度是多少.换句话说,找出"10%"是多少.

一旦您发现了这一点,您可以简单地将当前条宽度增加容器宽度的十分之一.我们还希望防止其增长超过100%.

function increaseProgress() {
  var progressBar = document.querySelector(".progress-bar")
  var progressContainer = document.querySelector(".progress-container")

  var barWidth = progressBar.clientWidth;
  var containerWidth = progressContainer.clientWidth;

  if (barWidth >= containerWidth) return;

  progressBar.style.width = (barWidth + containerWidth / 10) + "px";
}
.progress-container {
  width: 100%;
  height: 20px;
  outline: solid 2px #ccc;
  border-radius: 20px;
}

.progress-bar {
  width: 0;
  height: inherit;
  background: blue;
  border-radius: 20px;
}
<div class="progress-container">
  <div class="progress-bar"></div>
</div>
<button onclick="increaseProgress()">Click to increase</button>

Javascript相关问答推荐

如何将拖放功能添加到我已自定义为图像的文件输入HTML标签中?

RxJS setTimeout操作符等效

通过使用100%间隔时间来代表我们还剩多少时间来倒计时

网页自检测外部元素无法加载

判断表格单元格中是否存在文本框

使搜索栏更改语言

为什么promise对js中的错误有一个奇怪的优先级?

本地库中的chartjs-4.4.2和chartjs-plugin-注解

使用父标签中的Find函数查找元素

是否可以将异步调用与useState(UnctionName)一起使用

不同表的条件API端点Reaction-redux

如果对象中的字段等于某个值,则从数组列表中删除对象

在没有任何悬停或其他触发的情况下连续交换图像

表单数据中未定义的数组键

$GTE的mongoose 问题

如何在Firebase中读取对象的特定字段?

如何处理不带参数的redux thunk payloadCreator回调函数?

如何使用fltter_js将对象作为参数传递给javascrip?

单击时同时 Select 和展开可访问的行

我如何让我的弹力球在JavaScript和HTML画布中相互碰撞后改变 colored颜色 ?