以下是一个简单的实现方式:

HTML:

<button id="start">开始</button>
<div id="progress-bar">
  <div id="progress"></div>
  <div id="progress-text">0%</div>
</div>

CSS:

#progress-bar {
  position: relative;
  width: 100%;
  height: 30px;
  background-color: lightgray;
}

#progress {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background-image: linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet);
  width: 0%;
  transition: width 1s ease-in-out;
}

#progress-text {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
}

JavaScript:

const startButton = document.getElementById('start');
const progressBar = document.getElementById('progress');
const progressText = document.getElementById('progress-text');

startButton.addEventListener('click', () => {
  let progress = 0;
  const interval = setInterval(() => {
    progress++;
    progressBar.style.width = progress + '%';
    progressText.innerText = progress + '%';
    if (progress === 100) {
      clearInterval(interval);
    }
  }, 10);
});

效果:

点击开始按钮后,进度条会从0%到100%渐变显示,同时上面的数字会实时更新。进度条的颜色使用了彩虹渐变。

前端 帮我写一个进度条当点击按钮时会从0到100并且上面用数字显示当前的进度颜色要渐变的彩色

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

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