動畫文本
實現思路:
- 使用了
css3
的animation
動畫屬性 - 用
js
將文本拆分爲字符數組["今", "天", "不", "學", "習", " ", "~", " ", "明", "天", "變", "垃", "圾", " ", "~", " "]
- 循環數組,創建
span
元素,內容分別設爲每個字符,並設置不同的css
屬性animationDelay
(動畫開始時間) - 最後將
span
元素加入
html部分:
<p class="text">今天不學習 ~ 明天變垃圾 ~ </p>
scss部分:
body {
display: flex;
flex-direction: column;
height: 100vh;
justify-content: center;
align-items: center;
background-color: black;
}
.text {
display: flex;
flex-wrap: wrap;
color: white;
font-family: SimSun, serif;
white-space: pre;
font-size:28px;
span {
animation: textAnimation 1s ease-out both;
}
}
@keyframes textAnimation{
from {
opacity: 0;
transform: translateY(-40%);
}
to {
opacity: 1;
transform: translateY(0);
}
}
js部分:
// 1. 獲取DOM元素
let texts = document.querySelectorAll(".text");
// 2. 循環元素
texts.forEach(text => {
// 3. 將元素的文本內容分割成字符數組
let letters = text.textContent.split("");
// 4. 將內容清空
text.textContent = "";
// 5. 循環字符數組
letters.forEach((letter, i) => {
//6. 創建span元素,內容爲數組中的字符,設置動畫開始時間,最後將元素加入landInText
let span = document.createElement("span");
span.textContent = letter;
span.style.animationDelay = `${i * 0.1}s`;
text.append(span);
});
});
看懂了上面代碼後,修改scss
代碼裏動畫部分,又可以產生不同的效果:
舉一反N
修改一:
修改部分代碼:
.text {
display: flex;
flex-wrap: wrap;
color: white;
font-family: SimSun, serif;
white-space: pre;
font-size:28px;
span {
transform: translateY(100%);
animation: textAnimation 1s forwards; // forwards: 播放完動畫,停在定義的最後一幀
}
}
@keyframes textAnimation{
to {
transform: translateY(-12%);
}
}
修改二:
修改部分代碼:
.text {
display: flex;
flex-wrap: wrap;
color: rgb(139, 116, 134);
font-family: SimSun, serif;
white-space: pre;
font-size:24px;
font-weight: 600;
span {
padding: 5px;
line-height: 40px;
background: #eca6c3;
animation: textAnimation 2s infinite; // 設置infinite 無限動畫即不斷循環
}
}
@keyframes textAnimation{
50% {
box-shadow: 0 20px 0 #eee;
transform: translateY(-35px);
}
}
修改三:
修改部分代碼:
.text {
display: flex;
flex-wrap: wrap;
color: white;
font-family: SimSun, serif;
white-space: pre;
font-size:28px;
span {
animation: textAnimation 1.5s alternate infinite; // 設置infinite 無限動畫即不斷循環
}
}
@keyframes textAnimation{
to {
filter: blur(5px);
}
}
修改四:
修改部分代碼:
.text {
display: flex;
flex-wrap: wrap;
color: white;
font-family: SimSun, serif;
white-space: pre;
font-size:28px;
span {
animation: textAnimation 2s infinite; // 設置infinite 無限動畫即不斷循環
}
}
@keyframes textAnimation{
50% {
transform: scale(0);
}
}