代码来自于github上的50projects50days,我加了一些注释
效果图展示Blurry Loading(可能需要科学上网)
话不多说直接上代码(代码中的图片url和网址之类的可能需要科学上网,如果没有的话可以考虑欢称自己的图片)
大部分解释都在代码注释中,可能会随着天数的增加而减少代码(因为记住了)
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="index.css">
<title>模糊加载</title>
</head>
<body>
<section class="bg"></section>
<div class="loading-text">0%</div>
<script src="index.js"></script>
</body>
</html>
css
@import url('https://fonts.googleapis.com/css?family=Ubuntu');
* {
box-sizing: border-box;
}
body {
font-family: 'Ubuntu', sans-serif;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
overflow: hidden;
margin: 0;
}
.bg {
/* 背景图片 */
background: url('https://images.unsplash.com/photo-1576161787924-01bb08dad4a4?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2104&q=80')
no-repeat center center/cover;
position: absolute;
top: -30px;
left: -30px;
/* calc() 此 CSS 函数允许在声明 CSS 属性值时执行一些计算 */
width: calc(100vw + 60px);
height: calc(100vh + 60px);
z-index: -1;
/* filter 将模糊或颜色偏移等图形效果应用于元素。滤镜通常用于调整图像、背景和边框的渲染 */
filter: blur(0px);
}
.loading-text {
font-size: 50px;
color: #fff;
}
js
const loadText = document.querySelector('.loading-text')
const bg = document.querySelector('.bg')
let load = 0
// setInterval() 方法重复调用一个函数或执行一个代码片段,在每次调用之间具有固定的时间间隔。
let int = setInterval(blurring, 30)
function blurring() {
load++
// 设置停止Interval条件
if (load > 99) {
clearInterval(int)
}
// 更改百分比数字
loadText.innerText = `${load}%`
// opacity 属性指定了一个元素的不透明度,修改百分数的不透明度,数越大越不透明
loadText.style.opacity = scale(load, 0, 100, 1, 0)
// 更改图片的模糊程度
bg.style.filter = `blur(${scale(load, 0, 100, 30, 0)}px)`
}
// 函数原文解释https://stackoverflow.com/questions/10756313/javascript-jquery-map-a-range-of-numbers-to-another-range-of-numbers
// 将num从in_min--in_max区段映衬到out_min--out_max区段中
const scale = (num , in_min, in_max, out_min, out_max) => {
return ((num - in_min) * (out_max - out_min)) / (in_max - in_min) + out_min
}