如何让data-label的文本显示在progress进度条上方而非内部
进度条文本置顶实现方案
问题根源
原生<progress>是浏览器替换元素,不支持直接挂载::before/::after伪元素,你写在.ExpBar:before里的样式根本不会被浏览器渲染;就算伪元素生效,你也没有设置向上的定位偏移,文本会直接叠在进度条图层上,不会出现在上方。
另外你原有代码里火狐端的进度条样式写反了:::-moz-progress-bar对应的是进度填充区域,你之前给它设置了和底条一致的浅灰色,会导致火狐下看不到进度填充效果。
可直接运行的修正代码
用flex纵向布局实现最稳定,全浏览器兼容,不需要依赖兼容性差的伪元素方案:
样式代码
.exp_bar_container{ width:100%; top: 12em; position: relative; display:flex; flex-direction: column; gap: 6px; /* 控制文本和进度条的间距,可自行调整 */ } .ExpBar { height: 0.5em; width: 100%; background-color: #dcdcdc; position: relative; font-weight:bold; border: none; /* 清除浏览器默认progress边框 */ } .exp-bar-text { font-size: 0.8em; font-weight: bold; text-align: center; } /* 修正各浏览器进度条样式 */ .ExpBar::-moz-progress-bar { background: #630862; } .ExpBar::-webkit-progress-value { background: #630862; } .ExpBar::-webkit-progress-bar { background: #dcdcdc; }
结构代码
<div class="exp_bar_container"> <span class="exp-bar-text">20/20</span> <progress id="ExpBarId" class="ExpBar" value="1" max="100"></progress> </div>
动态更新说明
如果需要动态修改进度和对应文本,只需要在JS里同步修改两个属性即可:
// 示例:更新进度到50,文本改为50/100 const bar = document.getElementById('ExpBarId') const barText = document.querySelector('.exp-bar-text') bar.value = 50 barText.textContent = '50/100'
内容的提问来源于stack exchange,提问作者Jon Loftus
相关产品推荐
相关产品推荐

