主要思路:在一个容器中用display:flex + justify-content:space-between将几个块级元素水平均匀分布并且第一个元素和最后一个元素靠边,然后设置progress进度条和伪元素进度条样式一下且置于块级进度显示元素下方,用js实现点击按钮控制进度条长度变化
<!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>progress steps</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="container">
<div class="progress-container">
<div id="progress"></div>
<div class="circle active">1</div>
<div class="circle">2</div>
<div class="circle">3</div>
<div class="circle">4</div>
</div>
<button class="btn" id="pre">Prev</button>
<button class="btn" id="next">Next</button>
</div>
<script src="./script.js"></script>
</body>
</html>
:root {
--line-border-fill: #3498db;
--line-border-empty: #e0e0e0;
}
*{
box-sizing: border-box;
}
body{
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
overflow: hidden;
}
.container{
text-align: center;
}
.progress-container{
display: flex;
justify-content: space-between;
position: relative;
margin-bottom: 30px;
width: 350px;
}
.progress-container::before{
content: "";
position: absolute;
top: 50%;
left: 0;
transform: translateY(-50%);
width: 100%;
height: 4px;
background-color: var(--line-border-empty);
z-index: -1;
}
#progress{
position: absolute;
top: 50%;
left: 0;
transform: translateY(-50%);
width: 0%;
height: 4px;
background-color: var(--line-border-fill);
transition: all 0.4s ease;
z-index: -1;
}
.circle{
background-color: #fff;
color: #999;
border-radius: 50%;
width: 30px;
height: 30px;
display: flex;
align-items: center;
justify-content: center;
border: 3px solid var(--line-border-empty);
transition: all 0.4s ease;
}
.circle.active{
border-color: var(--line-border-fill);
}
.btn{
background-color: var(--line-border-fill);
color: #fff;
border: 0;
border-radius: 6px;
cursor: pointer;
padding: 8px 30px;
margin: 5px;
font-size: 14px;
}
.btn:active{
transform: scale(0.98);
}
.btn:focus{
outline: 0;
}
.btn:disabled{
background-color: var(--line-border-empty);
cursor: not-allowed;
}
const progress = document.querySelector('#progress')
const circleList = document.querySelectorAll('.circle')
const pre = document.querySelector('#pre')
const next = document.querySelector('#next')
let activeCount = 1
next.addEventListener('click', () => {
activeCount++
if (activeCount > circleList.length) {
activeCount = circleList.length
}
update()
})
pre.addEventListener('click', () => {
activeCount--
if (activeCount < 1) {
activeCount = 1
}
update()
})
function update () {
circleList.forEach((circle, index) => {
if (index < activeCount) {
circle.classList.add('active')
} else{
circle.classList.remove('active')
}
})
progress.style.width = (activeCount - 1) / (circleList.length - 1) * 100 + '%'
if (activeCount === 1) {
pre.disabled = true
} else if (activeCount === circleList.length) {
next.disabled = true
} else {
pre.disabled = false
next.disabled = false
}
}
效果展示
Q.E.D.