起因:
作为底层民工面试工作基本都要笔试,之前笔试遇到一道简单的题目是写一个加载的进度球,可我当时愣是没写出来。现在闲着没事写一下。
效果下图:
实现的代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.out {
position: relative;
width: 200px;
height: 200px;
border-radius: 50%;
background-color: #fff;
overflow: hidden;
}
.in {
position: absolute;
bottom: 0;
left: 0;
background-color: red;
height: 0px;
width: 100%;
overflow: hidden;
}
.out-percent {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
font-size: 52px;
color: red;
}
.in-percent {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
font-size: 52px;
color: #fff;
}
.gb {
position: absolute;
bottom: 0;
left: 0;
height: 200px;/* 与外层盒子保持一直 */
width: 100%;
}
.box {
background-color: antiquewhite;
font-weight: bold;
}
</style>
</head>
<body>
<div class="box">
<div class="out">
<div class="out-percent">0%</div>
<div class="in" style="height:0px">
<div class="gb">
<div class="in-percent">0%</div>
</div>
</div>
</div>
</div>
</body>
</html>
<script>
// 获取元素
var in_box = document.querySelector('.in')
var out_box = document.querySelector('.out')
var in_per = document.querySelector('.in-percent')
var out_per = document.querySelector('.out-percent')
// 每次递加的百分比
var addper = 10
// 设置定时器,实现自动加载
var timer = setInterval(() => {
var in_height = parseInt(in_box.style.height) + (addper * out_box.offsetWidth) /100
if (parseInt(in_height) > out_box.offsetWidth) {
clearInterval(timer)
return
}
in_box.style.height = in_height + 'px'
var per = parseInt(in_height/ out_box.offsetWidth * 100) + "%"
in_per.innerHTML = per
out_per.innerHTML = per
}, 1000);
</script>