要自制一个带有文字百分比的进度条,可以使用 CSS 的 '::after' 伪元素和 'content' 属性来实现。

首先,HTML 部分可以这样写:

<div class='progress-bar'>
  <div class='progress'></div>
</div>

然后,CSS 部分可以这样写:

.progress-bar {
  width: 300px;
  height: 20px;
  border: 1px solid #ccc;
  position: relative;
}

.progress {
  height: 100%;
  background-color: #00bcd4;
  width: 0;
  position: relative;
}

.progress::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #fff;
}

接下来,我们需要使用 JavaScript 来改变进度条的宽度和显示文字的内容。假设我们有一个按钮来触发进度条的增长,可以这样写:

<button onclick='increaseProgress()'>增加进度</button>

然后,在 JavaScript 部分写入以下代码:

function increaseProgress() {
  var progress = document.querySelector('.progress');
  var currentWidth = parseInt(progress.style.width) || 0;
  var newWidth = currentWidth + 10;
  
  if (newWidth > 100) {
    newWidth = 100;
  }
  
  progress.style.width = newWidth + '%';
  progress.setAttribute('data-percent', newWidth + '%');
}

这段代码中,我们使用 querySelector 方法选择进度条元素,并获取当前的宽度值。然后,根据按钮点击的次数,将新的宽度值加上 10,并设置进度条的宽度和 data-percent 属性,用来显示百分比。

最后,我们需要修改 CSS 来显示百分比:

.progress::after {
  content: attr(data-percent);
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #fff;
}

现在,每次点击按钮,进度条会增加 10%,并在中间显示当前的百分比。

纯 CSS 自制带文字百分比的进度条

原文地址: http://www.cveoy.top/t/topic/pYDc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录