文章目录
前言
一、实现方法
二、实现
1.html
2.设置背景
3.设置进度条样式
4.显示百分比
5.最终效果
前言
使用html,css和javascript 实现一个简单的进度条效果
一、实现方法
嵌套两个div,其中子div通过动画改变自身宽度来实现进度条效果。
使用JavaScript来计算其百分比来显示百分比数字。
二、实现
1.html
代码如下:
<body> <div id="border"> <div id="progress"></div> </div> <div id="rop"> <input type="text" id="rate" value="0"> </div> </body>
复制
#border用来实现进度条,#rop来实现百分比。
2.设置背景
代码如下:
body{ width: 100vw; height: 100vh; display: grid; grid-template-columns: 350px; grid-template-rows: 25px 130px; grid-template-areas: 'area1' 'area2'; justify-content: center; align-content: center; background: #ff9933; }
复制
开启一个一行两列的网格布局,并将子元素居中显示
3.设置进度条样式
父div样式:
#border{ grid-area: area1; width: 350px; height: 25px; border: 2px solid #666; border-radius: 5px; box-shadow: 0 0 10px #ccc; display: flex; align-items: center; }
复制
它将作为进度条的边框部分显示。
子div样式:
#progress{ height: 23px; border-radius: 5px; box-shadow: 0 0 2px #ff3300; background-image: linear-gradient(to right, #ff6600,#cc3300); animation: move 5s infinite; }
复制
动画:
@keyframes move{ 0%{ width: 0%; } 100%{ width: 100%; } }
复制
通过动画使子div在5s内改变自己的宽度从而实现了进度条效果
4.显示百分比
这里使通过将上述两个div的宽度相除来得到百分比。
css样式:
#rop{ grid-area: area2; justify-self: center; align-self: center; } #rate{ width: 60px; height: 35px; border: 2px solid #666; border-radius: 5px; box-shadow: 0 0 10px #ccc; background-color: #ff9933; font-size: 20px; text-align: center; pointer-events: none; }
复制
JavaScript代码:
let oborder = document.querySelector('#border'); let oprogress = document.querySelector('#progress'); let orate = document.querySelector('#rate'); setInterval(() =>{ let percent = Math.floor((oprogress.clientWidth / oborder.clientWidth)*100) + '%'; orate.value = percent; },200)
复制
直接用JavaScript相除得到的是小数所以需要取整。
5.最终效果
这里是完整的css样式
*{ margin: 0; padding: 0; } body{ width: 100vw; height: 100vh; display: grid; grid-template-columns: 350px; grid-template-rows: 25px 130px; grid-template-areas: 'area1' 'area2'; justify-content: center; align-content: center; background: #ff9933; } #border{ grid-area: area1; width: 350px; height: 25px; border: 2px solid #666; border-radius: 5px; box-shadow: 0 0 10px #ccc; display: flex; align-items: center; } #progress{ height: 23px; border-radius: 5px; box-shadow: 0 0 2px #ff3300; background-image: linear-gradient(to right, #ff6600,#cc3300); animation: move 5s infinite; } @keyframes move{ 0%{ width: 0%; } 100%{ width: 100%; } } #rop{ grid-area: area2; justify-self: center; align-self: center; } #rate{ width: 60px; height: 35px; border: 2px solid #666; border-radius: 5px; box-shadow: 0 0 10px #ccc; background-color: #ff9933; font-size: 20px; text-align: center; pointer-events: none; }
复制