进度条已经是司空见惯的东西,那么今天我们用原生JS实现一个加载进度条,并且实现随机颜色。
1.Html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>简单进度条</title>
</head>
<body>
<!-- 进度条容器 -->
<div class="main">
<!-- 进度变化容器 -->
<div class="main_content">
<!-- 进度文字显示 -->
<span class="span"></span>
</div>
</div>
<!-- 随机颜色提示信息 -->
<div class="index">
</div>
</body>
</html>
2.Css
<style>
.main {
width: 500px;
height: 50px;
border: 1px solid #000;
line-height: 50px;
font-size: 20px;
font-weight: 600;
border-radius: 30px;
}
.main_content {
border-radius: 30px;
height: 100%;
}
.span {
float: right;
border-radius: 30px;
}
.index {
width: 800px;
}
</style>
3.JS
<script>
(function () {
//获取元素
let div = document.querySelector('.main');
let content = document.querySelector('.main_content');
let span = document.querySelector('.span')
let index = document.querySelector('.index')
//定义进度变量
let i = 0;
//定时器进行实现
let time = setInterval(() => {
if (i > 99) {
//移除定时器
clearInterval(time)
time = null
} else {
i++;
content.style.width = i + '%';
span.innerHTML = i + '%';
//随机颜色
let r = Math.round(Math.random() * 225)
let g = Math.round(Math.random() * 225)
let b = Math.round(Math.random() * 225)
//改变进度颜色
content.style.backgroundColor = "rgb(" + r + ',' + g + ',' + b + ")";
index.innerText += `当前${i}%的颜色:(${r + ',' + g + ',' + b})`
index.style.color = "rgb(" + r + ',' + g + ',' + b + ")"
}
}, 50);
})()
</script>