CSS3動畫:動畫文本

動畫文本

在這裏插入圖片描述

實現思路:

  • 使用了css3animation 動畫屬性
  • 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);
    }
  }

在這裏插入圖片描述
推薦閱讀:前端實現動畫的方法彙總 ٩( ‘ω’ )و

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章