在實作首頁打字動畫時,參考其他人實作過的CSS打字動畫(範例)
但發現CSS屬性中 white-space: nowrap;
會導致無法滿足RWD的換行需求
因此捨棄純CSS方法,配合JavaScript來實踐
HTML
<h1 class="mb-0">{{ animatedText }}<span id="caret"> </span></h1>
{{animatedText}}
為Vue data的一個變數;後方的<span>是用來實踐結尾的閃爍打字符
Script in Vue
<script>
export default {
data() {
return {
sloganText: "Welcome to Hamsterism, Eide's Blog!",
animatedText: "",
i: 0,
};
},
watch: {
animatedText(newV) {
if (newV === this.sloganText) {
setTimeout(() => {
//注意這裡必須使用arrow function才能讓this被正確指向
this.i = 0;
this.animatedText = "";
this.typeWriter();
}, 10000);
}
},
},
created() {
setTimeout(() => this.typeWriter(), 1000);
},
methods: {
typeWriter() {
const speed = 100;
if (this.i < this.sloganText.length) {
this.animatedText += this.sloganText.charAt(this.i);
this.i++;
setTimeout(this.typeWriter, speed);
}
},
},
};
</script>
透過for迴圈配合setTimeout的方式,每隔100ms添加一字,產生打字動畫效果
最後用watch監控輸出的字串長度,當指定字串被完整輸入後,
設定10秒後重置為空字串,再次跑一次打字動畫
CSS
#caret {
border-left: 5px solid orange;
margin-left: 3px;
animation: blink-caret 1s infinite;
}
@keyframes blink-caret {
from {
border-color: transparent;
}
to {
border-color: orange;
}
}
使用span的左邊界實作閃爍效果
完成!