如何为网站实现类似YouTube的灰色长条内容预加载效果?
嘿,我刚好做过类似的效果,给你分享一个简单易实现的方案,完全能达到你想要的YouTube式灰色长条预加载效果👇
实现步骤
这个方案只需要HTML+CSS+少量JS,就能还原那种渐变闪烁的加载条效果,具体代码如下:
1. HTML 结构
先创建预加载器的容器和几个加载条,模拟不同长度的内容块:
<!-- 预加载器容器 --> <div class="preloader-container"> <div class="preloader-item"></div> <div class="preloader-item"></div> <div class="preloader-item"></div> <div class="preloader-item"></div> </div>
2. CSS 样式
核心是用线性渐变和动画实现闪烁效果,同时调整每个条的宽度来模拟真实内容的排版:
/* 预加载器容器样式 */ .preloader-container { width: 100%; max-width: 600px; /* 可根据页面布局调整最大宽度 */ margin: 20px auto; display: flex; flex-direction: column; gap: 8px; /* 控制条之间的间距 */ } /* 单个预加载条基础样式 */ .preloader-item { height: 16px; /* 条的高度,标题可以设为24px左右 */ background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; border-radius: 4px; /* 圆角让风格更柔和,贴近YouTube */ animation: loading-shimmer 1.5s infinite linear; } /* 给不同条设置不同宽度,模拟真实内容的长短差异 */ .preloader-item:nth-child(1) { width: 100%; } .preloader-item:nth-child(2) { width: 90%; } .preloader-item:nth-child(3) { width: 75%; } .preloader-item:nth-child(4) { width: 85%; } /* 关键帧动画:实现渐变背景的左右移动,模拟加载中的闪烁感 */ @keyframes loading-shimmer { 0% { background-position: -200% 0; } 100% { background-position: 200% 0; } }
3. JavaScript 控制显示/隐藏
当页面或异步内容加载完成后,隐藏预加载器:
// 页面全部资源加载完成后隐藏 window.addEventListener('load', () => { const preloader = document.querySelector('.preloader-container'); if (preloader) { // 可以添加淡出动画让过渡更自然 preloader.style.opacity = '0'; setTimeout(() => preloader.style.display = 'none', 500); } }); // 如果是加载异步数据(比如接口返回内容),可以在数据成功后调用这个函数 function hidePreloader() { const preloader = document.querySelector('.preloader-container'); if (preloader) { preloader.style.opacity = '0'; setTimeout(() => preloader.style.display = 'none', 500); } }
自定义小技巧
- 可以调整
.preloader-item的height来区分标题和段落:比如标题设为24px,段落设为16px - 动画速度可以修改
animation里的1.5s,数值越小动画越快,反之则越慢 - 颜色可以根据你的网站主题调整,把
#f0f0f0和#e0e0e0换成你需要的灰色系
内容的提问来源于stack exchange,提问作者Karamellwuerfel
相关产品推荐
相关产品推荐

