50 天学习 50 个项目 - HTMLCSS and JavaScript
day05-blurry-loading(模糊加载)
效果
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blurry loading</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<!-- 背景 -->
<section class="bg"></section>
<!-- 加载文本 -->
<div class="loading-text">0%</div>
<script src="script.js"></script>
</body>
</html>
style.css
@import url('https://fonts.googleapis.com/css?family=Ubuntu');
/* 从 Google Fonts 中导入名为 "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;
width: calc(100vw + 60px);
height: calc(100vh + 60px);
/* 通过 calc() 函数,将视口高度、宽度和额外的 60 像素相加,得到最终的高度值、宽度值。 */
z-index: -1;
/* 置于底部,不覆盖加载文本*/
filter: blur(0px);
/* 将元素的模糊程度设置为 0 像素,即不模糊。 */
}
/* 加载文本 */
.loading-text {
font-size: 50px;
color: #fff;
}
script.js
// 重点是felx z-index background 的应用
// 1.获取元素节点
const loadText = document.querySelector('.loading-text');//加载文本
const bg = document.querySelector('.bg');//背景
// 加载值
let load = 0
// 开启定时器中,按照指定的时间间隔周期性地执行指定的代码或函数。
let int = setInterval(() => {
load++;
// 这是一个实现线性缩放的 JavaScript 箭头函数 scale。它接受五个参数,分别是要缩放的数值 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;
// 这个公式将 num 的值从输入范围 [in_min, in_max] 映射到输出范围 [out_min, out_max],并返回映射后的结果。
}
if (load > 99) {
// 大于99,清除定时器
clearInterval(int);
}
// 设置加载文本,使用模板字符串
loadText.innerText = `${load}%`;
// 设置加载文本的透明度,最终为0,透明
loadText.style.opacity = scale(load, 0, 100, 1, 0);
// 设置背景的模糊度,最终不模糊
bg.style.filter = `blur(${scale(load, 0, 100, 30, 0)}px)`;
}, 30)