按下右側的「點擊預覽」按鈕能夠在當前頁面預覽,點擊連接能夠全屏預覽。css
https://codepen.io/comehope/pen/ELpRxjhtml
此視頻是能夠交互的,你能夠隨時暫停視頻,編輯視頻中的代碼。前端
請用 chrome, safari, edge 打開觀看。git
https://scrimba.com/c/czrWDfZgithub
每日前端實戰系列的所有源代碼請從 github 下載:web
https://github.com/comehope/front-end-daily-challengesspring
定義 dom,容器中包含文本,而且包含4個 <span> 用於特效,<span> 的 data-text 屬性值爲與文本相同:chrome
<p class="rainbow"> web <span data-text="web"></span> <span data-text="web"></span> <span data-text="web"></span> <span data-text="web"></span> </p>
居中顯示:dom
html, body { height: 100%; display: flex; align-items: center; justify-content: center; background: black; }
定義文本樣式:flex
.rainbow { color: white; font-size: 300px; text-transform: uppercase; font-family: sans-serif; font-weight: bold; line-height: 1em; position: relative; }
用僞元素增長圖層,造成彩虹效果:
.rainbow span::before, .rainbow span::after { content: attr(data-text); position: absolute; top: 0; left: 0; overflow: hidden; } .rainbow span:nth-child(1)::before { color: orchid; z-index: 1; height: calc(100% - 10% * 1); } .rainbow span:nth-child(1)::after { color: mediumpurple; z-index: 2; height: calc(100% - 10% * 2); } .rainbow span:nth-child(2)::before { color: deepskyblue; z-index: 3; height: calc(100% - 10% * 3); } .rainbow span:nth-child(2)::after { color: cyan; z-index: 4; height: calc(100% - 10% * 4); } .rainbow span:nth-child(3)::before { color: mediumspringgreen; z-index: 5; height: calc(100% - 10% * 5); } .rainbow span:nth-child(3)::after { color: yellow; z-index: 6; height: calc(100% - 10% * 6); } .rainbow span:nth-child(4)::before { color: gold; z-index: 7; height: calc(100% - 10% * 7); } .rainbow span:nth-child(4)::after { color: tomato; z-index: 8; height: calc(100% - 10% * 8); }
增長動畫效果:
.rainbow span::before, .rainbow span::after { animation: animate 0.8s infinite alternate; filter: opacity(0); } @keyframes animate { from { filter: opacity(0); } to { filter: opacity(1); } }
爲圖層設置延時,加強動感:
.rainbow span:nth-child(1)::before { animation-delay: calc(0.8s - 0.1s * 1); } .rainbow span:nth-child(1)::after { animation-delay: calc(0.8s - 0.1s * 2); } .rainbow span:nth-child(2)::before { animation-delay: calc(0.8s - 0.1s * 3); } .rainbow span:nth-child(2)::after { animation-delay: calc(0.8s - 0.1s * 4); } .rainbow span:nth-child(3)::before { animation-delay: calc(0.8s - 0.1s * 5); } .rainbow span:nth-child(3)::after { animation-delay: calc(0.8s - 0.1s * 6); } .rainbow span:nth-child(4)::before { animation-delay: calc(0.8s - 0.1s * 7); } .rainbow span:nth-child(4)::after { animation-delay: calc(0.8s - 0.1s * 8); }
最後,把原始文本設置爲透明色:
.rainbow { color: transparent; }
大功告成!