用HTML5、css和JavaScript写一个功能页面上有个一进度条要求实现点击按钮进度条缓慢变为100并且进度条上会显示进度数字百分号
以下是一个示例实现:
HTML代码:
<div class="progress">
<div class="progress-bar" role="progressbar"></div>
<div class="progress-text">0%</div>
</div>
<button id="start-btn">Start</button>
CSS代码:
.progress {
width: 400px;
height: 20px;
background-color: #eee;
position: relative;
}
.progress-bar {
width: 0%;
height: 100%;
background-color: #007bff;
position: absolute;
top: 0;
left: 0;
}
.progress-text {
position: absolute;
top: 2px;
right: 5px;
font-size: 14px;
}
JavaScript代码:
var progressBar = document.querySelector('.progress-bar');
var progressText = document.querySelector('.progress-text');
var startBtn = document.querySelector('#start-btn');
startBtn.addEventListener('click', function() {
var progress = 0;
var intervalId = setInterval(function() {
progress += 1;
progressBar.style.width = progress + '%';
progressText.textContent = progress + '%';
if (progress >= 100) {
clearInterval(intervalId);
}
}, 20);
});
解释:
首先,我们用HTML代码创建了一个进度条和一个按钮。进度条包括一个进度条元素和一个进度文本元素。按钮用于触发进度条动画。
然后,我们用CSS代码为进度条和按钮添加了样式。进度条用了绝对定位来实现进度条的宽度变化。文本元素用了绝对定位来实现进度百分比的显示。
最后,我们用JavaScript代码实现了进度条的动画效果。当按钮被点击时,我们使用setInterval函数来定时更新进度条的宽度和文本内容,直到进度条达到100%。在这个过程中,我们还使用了clearInterval函数来停止定时更新。
原文地址: https://www.cveoy.top/t/topic/MhP 著作权归作者所有。请勿转载和采集!