<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> :root{ /*定义颜色常量*/ --line-border-fill: #3498db; --line-border-empty: #e0e0e0; } *{ margin: 0; padding: 0; box-sizing: border-box; } body{ background-color: #f6f7f6; font-family: sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; } .container{ text-align: center; } .progrese-container{ display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; width: 350px; position: relative; } .progrese-container::before{ content: ""; background-color: var(--line-border-empty); height: 4px; width: 100%; position: absolute; top: 50%; transform: translateY(-50%); z-index: -1; } .progress{ background-color: var(--line-border-fill); position: absolute; height: 4px; transform: translateY(-50%); width: 0%; top: 50%; z-index: -1; transition: all .3s ease-in-out; } .circle{ background-color: white; color: #999; width: 30px; height: 30px; display: flex; justify-content: center; align-items: center; border: 3px solid var(--line-border-empty); border-radius: 50%; } .circle.active{ border-color: var(--line-border-fill); } .btn{ background-color: var(--line-border-fill); color: #fff; border-radius: 5px; border: 0; font-size: 14px; margin: 5px; padding: 8px 30px; } .btn:active{ transform: scale(0.98); } .btn:focus{ outline: none; } .btn:disabled{ background-color: var(--line-border-empty); cursor: not-allowed; } </style> </head> <body> <div class="container"> <div class="progrese-container"> <div class="progress" 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="prev" disabled>Prev</button> <button class="btn" id="next" >Next</button> </div> <script> const progress = document.getElementById('progress'); const prev = document.getElementById('prev'); const next = document.getElementById('next'); const circles = document.querySelectorAll('.circle'); //定义一个常量来来控制判断是否要用disabled。 let currentActive = 1; next.addEventListener('click',()=>{ currentActive++; update(); }) prev.addEventListener('click',()=>{ currentActive--; update() }) function update() { circles.forEach((item,index)=>{ if(index<currentActive){ //如果没有到达最后一点,就给每一个点添加active来控制按钮的颜色。 item.classList.add('active') } else{ //点击了prev,这个时候index就等于currentActive,这时候就让按钮的颜色变灰。 item.classList.remove('active') } //蓝色长条的长度控制。点击next宽度就加总长度的33% progress.style.width = (currentActive - 1)/(circles.length-1)*100+"%" }) if(currentActive < 2){ //当点击prev到了第一个就变成灰色,不能点击 prev.disabled = true }else { //其他情况就可以点击 prev.disabled = false } if(currentActive < 4){ //如果没有到达最后就可以点击next。 next.disabled = false }else { //到了最后就不能点击了。 next.disabled = true } } </script> </body> </html>