一、效果预览
二、效果实现
在 Vue3
单页面应用中,启动动画是提升用户体验的一个重要环节。本文介绍了一种常见的启动动画实现方式,通过在 Vue
挂载前显示一个加载动画,直到 Vue
组件加载完成并替换内容。
2.1、HTML 结构
<!-- VueJS 挂载的 DOM 容器 -->
<div id="app">
<div class="app-loading">
<div class="app-loading-wrap">
<img src="/src/assets/images/logo.png" class="app-loading-logo" alt="Logo" />
<div class="app-loading-dots">
<span class="dot dot-spin"><i></i><i></i><i></i><i></i></span>
</div>
<div class="app-loading-title"><%= VITE_APP_TITLE %></div>
</div>
</div>
</div>
2.2、CSS 样式
.app-loading {
position: fixed;
top: 0;
left: 0;
z-index: 999999;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
width: 100%;
height: 100%;
font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
background-color: #f5f6f7;
}
.app-loading .app-loading-wrap {
position: absolute;
top: 50%;
left: 50%;
display: flex;
transform: translate3d(-50%, -50%, 0);
justify-content: center;
align-items: center;
flex-direction: column;
}
.app-loading .dots {
display: flex;
align-items: center;
justify-content: center;
padding: 98px;
}
.app-loading .app-loading-title {
display: flex;
align-items: center;
justify-content: center;
margin-top: 32px;
font-size: 30px;
color: rgba(0, 0, 0, 0.85);
}
.app-loading .app-loading-logo {
display: block;
width: 90px;
}
.dot {
position: relative;
display: inline-block;
width: 48px;
height: 48px;
margin-top: 30px;
font-size: 32px;
transform: rotate(45deg);
box-sizing: border-box;
animation: antRotate 1.2s infinite linear;
}
.dot i {
position: absolute;
display: block;
width: 20px;
height: 20px;
background-color: #0065cc;
border-radius: 100%;
opacity: 0.3;
transform: scale(0.75);
animation: antSpinMove 1s infinite linear alternate;
transform-origin: 50% 50%;
}
.dot i:nth-child(1) {
top: 0;
left: 0;
}
.dot i:nth-child(2) {
top: 0;
right: 0;
animation-delay: 0.4s;
}
.dot i:nth-child(3) {
right: 0;
bottom: 0;
animation-delay: 0.8s;
}
.dot i:nth-child(4) {
bottom: 0;
left: 0;
animation-delay: 1.2s;
}
@keyframes antRotate {
to {
transform: rotate(405deg);
}
}
@keyframes antSpinMove {
to {
opacity: 1;
}
}
2.3、详细解析
.app-loading
容器使用position: fixed
将其固定在屏幕的最前端,并设置全屏的宽高。通过flex
布局,使得内容居中显示。同时使用了浅灰色背景#f5f6f7
,确保页面加载时视觉效果干净且不会干扰用户.app-loading-wrap
包裹层居中放置了 Logo、加载动画以及标题。通过translate3d(-50%, -50%, 0)
将该元素移动到页面的中心,确保其在不同屏幕尺寸下都保持居中- 每个
.dot
内部包含四个小圆点,这些小圆点会进行旋转的同时,透明度逐渐变化(从不透明到完全透明)。通过animation-delay
控制各个圆点的动画开始时间,错开它们的动画时机,形成动态的渐变效果 antSpinMove
动画控制每个小圆点的透明度变化。使用opacity
属性让圆点逐渐变得更加明显,达到动感效果
三、使用场景
这段代码可以应用于 Vue3
的启动动画,在页面加载过程中保持用户的关注,同时在 Vue
组件加载完成后,自动过渡到实际的应用页面。通过这种方式,可以有效提高用户体验,避免页面加载时的空白等待。