通过CSS 和 JS 实现,打开网页加载的过程中,进度条跟随网页的加载速度而载入,直到网页加载完毕后隐藏;

HTML代码
<div id="progress-bar"></div>
CSS代码
#progress-bar {
position: fixed;
top: 0;
left: 0;
width: 0;
height: 5px;
background-color: #4caf50;
transition: width 0.3s linear;
z-index: 9999;
}
JS代码
// 创建一个变量来追踪加载进度
let loadProgress = 0;
let progressBar;
// 当DOM加载开始时初始化进度条
document.addEventListener('DOMContentLoaded', function() {
progressBar = document.getElementById('progress-bar');
progressBar.style.width = '0%';
progressBar.style.display = 'block';
// 快速增加到60%
loadProgress = 60;
progressBar.style.width = loadProgress + '%';
});
// 页面完全加载时完成进度条
window.addEventListener('load', function() {
// 从当前进度平滑过渡到100%
let interval = setInterval(function() {
if (loadProgress >= 100) {
clearInterval(interval);
// 完成后延迟隐藏进度条
setTimeout(function() {
progressBar.style.display = 'none';
}, 500);
return;
}
loadProgress += 2;
progressBar.style.width = loadProgress + '%';
}, 20);
});
// 如果加载时间过长,缓慢增加进度
let slowProgress = setInterval(function() {
if (loadProgress >= 90) {
clearInterval(slowProgress);
return;
}
if (loadProgress < 90) {
loadProgress += 0.5;
if (progressBar) {
progressBar.style.width = loadProgress + '%';
}
}
}, 100);

评论(0)
暂无评论