JS新手如何实现带加减按钮、支持local storage存储的进度条?
阅读进度计数功能实现方案
你可以直接按照下面的结构、样式、逻辑三段代码整合到你的项目中,所有需求功能都已覆盖:
1. HTML结构
<!-- 顶部进度条组件 --> <div class="read-progress-wrap"> <button id="decreaseBtn">-</button> <div class="progress-bar"> <div class="progress-fill"></div> </div> <button id="increaseBtn">+</button> <p class="progress-tip" id="progressTip"></p> </div>
2. CSS样式
你可以根据自己的页面风格调整颜色、尺寸、定位参数:
.read-progress-wrap { position: fixed; top: 0; left: 0; width: 100%; display: flex; align-items: center; gap: 12px; padding: 10px 20px; background: #fff; box-shadow: 0 2px 4px rgba(0,0,0,0.1); z-index: 999; box-sizing: border-box; } .read-progress-wrap button { width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; border: 1px solid #ddd; border-radius: 4px; background: #f5f5f5; cursor: pointer; } .progress-bar { flex: 1; height: 12px; background: #e5e5e5; border-radius: 6px; overflow: hidden; } .progress-fill { height: 100%; width: 0%; background: #2563eb; transition: width 0.2s ease; } .progress-tip { margin: 0; font-size: 14px; color: #333; white-space: nowrap; }
3. JS交互逻辑
// 配置项:总阅读数可根据需求修改 const TOTAL_READ = 30 // 读取本地存储的已读数量,首次加载默认是0 let readCount = Number(localStorage.getItem('readCount')) || 0 // 页面元素获取 const decreaseBtn = document.getElementById('decreaseBtn') const increaseBtn = document.getElementById('increaseBtn') const progressFill = document.querySelector('.progress-fill') const progressTip = document.getElementById('progressTip') // 统一更新视图函数 function updateView() { // 更新提示文本,不展示百分比 progressTip.innerText = `你已阅读30本中的${readCount}本` // 进度条按已读数量比例填充 const percent = (readCount / TOTAL_READ) * 100 progressFill.style.width = `${percent}%` } // 减按钮点击事件:限制最小数量为0 decreaseBtn.addEventListener('click', () => { if (readCount <= 0) return readCount-- localStorage.setItem('readCount', readCount) updateView() }) // 加按钮点击事件:限制最大数量为总阅读数 increaseBtn.addEventListener('click', () => { if (readCount >= TOTAL_READ) return readCount++ localStorage.setItem('readCount', readCount) updateView() }) // 页面加载时初始化展示内容 updateView()
可选调整说明
- 如果需要修改总阅读量,直接修改JS里的
TOTAL_READ常量,同时同步修改提示文本里的固定数值即可 - 如果页面已有固定顶部的导航栏,可以调整
.read-progress-wrap的top属性值避免互相遮挡 - localStorage存储的数据不会随页面刷新、浏览器关闭丢失,只要用户不手动清除浏览器缓存就会一直保留
内容的提问来源于stack exchange,提问作者Karla
相关产品推荐
相关产品推荐

