向您的网站添加加载器
大家好,今天我们来学习如何在网站上添加加载器!加载器的应用由来已久,事实证明,网站上有加载器时,用户会更有耐心。因此,我建议设置一个加载器,使其在整个页面加载完成后自动消失。
第一步
首先,我们将设置 HTML:
-
<div>
带有 id 的标签将containerLoader
保存加载器(顾名思义😉)。 -
而
<div>
具有类的标签containerText
将允许包含页面的所有内容,包括文本和图像
<body>
<div id="containerLoader" class="containerLoader">
<div class="lds-ripple">
<div></div>
<div></div>
</div>
</div>
<div class="containerText">
<h1>I'm the title</h1>
<p>Your text here</p>
</div>
</body>
第二步
现在我们用一些 CSS 设置我们的加载器。
.lds-ripple {
display: inline-block;
position: relative;
width: 80px;
height: 80px;
}
.lds-ripple div {
position: absolute;
border: 4px solid #fff;
opacity: 1;
border-radius: 50%;
animation: lds-ripple 1s cubic-bezier(0, 0.2, 0.8, 1) infinite;
}
.lds-ripple div:nth-child(2) {
animation-delay: -0.5s;
}
@keyframes lds-ripple {
0% {
top: 36px;
left: 36px;
width: 0;
height: 0;
opacity: 1;
}
100% {
top: 0px;
left: 0px;
width: 72px;
height: 72px;
opacity: 0;
}
}
您可以在下面看到加载动画的结果:
第三步
现在我们将设计我们的页面样式:
@import url("https://fonts.googleapis.com/css2?family=Roboto&display=swap");
body {
background: #252525;
color: white;
font-family: "Roboto", sans-serif;
margin: 0 5% 0 5%;
}
.containerText {
display: block;
margin: 0 auto;
width: 900px;
max-width: 90%;
}
.containerText p {
text-align: justify;
}
.containerText h1 {
text-align: center;
}
/* The disappearing animation of the loader */
@keyframes hide {
from {
opacity: 1;
}
to {
opacity: 0;
display: none;
}
}
.hide {
animation: hide 1s;
animation-iteration-count: 1;
}
/* The loader container */
#containerLoader {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100%;
height: 100%;
display: block;
background: black;
}
/* This last piece of code is purely aesthetic and optional. */
::-moz-selection {
background: rgba(255, 255, 255, 0.22);
}
::selection {
background: rgba(255, 255, 255, 0.22);
}
最后一步
最后,我们设置一下 JavaScript,这样当页面准备好显示时,加载器就会消失。对某些人来说,这是一个很好的建议:我们不会使用 jQuery。
document.onreadystatechange = () => {
if (document.readyState === 'complete') {
document.getElementById("containerLoader").classList.add('hide');
setTimeout(function(){
document.getElementById("containerLoader").style.display = 'none';
}, 1000);
}
};
结果
您可以在下方看到我们加载器的最终效果。如果动画太快,您可以点击“重新运行”按钮重新开始动画。
我希望本教程对您有用,如果您愿意,请随时在您的网站上使用它,并在评论中告诉我您的意见。👍
鏂囩珷鏉ユ簮锛�https://dev.to/clementgaudiniere/add-a-loader-to-your-website-eag