预加载效果通常使用 CSS3 中的动画来实现。其中,关键的 CSS 属性包括 @keyframes、animation、animation-delay、animation-iteration-count 等。
下面是一个简单的预加载效果的 CSS 代码示例:
/* 定义动画关键帧 */
@keyframes loading {
0% {
width: 0;
}
100% {
width: 100%;
}
}
/* 定义动画 */
.loading-bar {
position: fixed;
top: 0;
left: 0;
height: 3px;
width: 0;
background-color: #007bff;
animation: loading 2s ease-in-out infinite;
}
/* 延迟加载 */
body.loading::before {
content: '';
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #fff;
z-index: 99999;
}
/* 停止加载 */
body.loaded::before {
animation: fade-out 0.5s ease-in-out;
animation-fill-mode: forwards;
}
/* 关键帧 */
@keyframes fade-out {
0% {
opacity: 1;
}
100% {
opacity: 0;
display: none;
}
}
其中,.loading-bar
是预加载的动画效果,通过 animation
属性定义了动画的名称、时长、缓动函数和循环次数。body.loading::before
和 body.loaded::before
是用于延迟加载和停止加载的背景层,通过 content
、position
、width
、height
、background
和 z-index
属性定义了背景层的样式,通过 animation
和 animation-fill-mode
属性来实现动画效果。
在 HTML 中,可以通过 JavaScript 来控制预加载的状态,例如:
// 开始加载
document.body.classList.add('loading');
// 加载完成
document.body.classList.add('loaded');
这样就可以实现一个简单的预加载效果了。