本篇文章給大家帶來的內容是關於如何使用純CSS實現文字斷開的動畫效果(附源碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所協助。
效果預覽
原始碼下載
https://github.com/comehope/front-end-daily-challenges/tree/master/012-broken-text-effects
代碼解讀
定義 dom,只有一個元素,元素有一個 data-text 屬性,屬性值等於元素內的文本:
<div class="text" data-text="BREAK">BREAK</div>
置中顯示:
html, body { height: 100%; display: flex; align-items: center; justify-content: center;}
設定漸層背景色:
body { background: linear-gradient(brown, sandybrown);}
設定文本的字型字型大小:
.text { font-size: 5em; font-family: "arial black";}
利用虛擬元素增加文字:
.text { position: relative;}.text::before,.text::after { content: attr(data-text); position: absolute; top: 0; left: 0; color: lightyellow;}
設定左側文字的遮罩:
.text::before { background-color: darkgreen; clip-path: polygon(0 0, 60% 0, 30% 100%, 0 100%);}
設定右側文字的背景和遮罩:
.text::after { background-color: darkblue; clip-path: polygon(60% 0, 100% 0, 100% 100%, 30% 100%);}
當滑鼠划過時,遮罩的文字分別向兩側位移:
.text::before,.text::after { transition: 0.2s;}.text:hover::before { left: -0.15em;}.text:hover::after { left: 0.15em;}
隱藏輔助元素,包括原始文字和虛擬元素的背景色:
.text { color: transparent;}.text::before { /*background-color: darkgreen;*/}.text::after { /*background-color: darkblue;*/}
兩側文字增加歪斜效果:
.text:hover::before { transform: rotate(-5deg);}.text:hover::after { transform: rotate(5deg);}
微調文字的高度:
.text:hover::before { top: -0.05em;}.text:hover::after { top: 0.05em;}
大功告成!