如何用純 CSS 創作背景色塊變換的按鈕特效
阿新 • • 發佈:2018-11-23
效果預覽
按下右側的“點選預覽”按鈕可以在當前頁面預覽,點選連結可以全屏預覽。
https://codepen.io/comehope/pen/XYKdwg
可互動視訊教程
此視訊是可以互動的,你可以隨時暫停視訊,編輯視訊中的程式碼。
請用 chrome, safari, edge 開啟觀看。
https://scrimba.com/p/pEgDAM/cM7RLUG
原始碼下載
本地下載
每日前端實戰系列的全部原始碼請從 github 下載:
https://github.com/comehope/front-end-daily-challenges
程式碼解讀
定義 dom,標準導航結構下,<li> 中的每個字母用 <span> 包裹:
<nav> <ul> <li> <span>p</span> <span>r</span> <span>o</span> <span>d</span> <span>u</span> <span>c</span> <span>t</span> <span>s</span> </li> </ul> </nav>
居中顯示:
body {
margin: 0;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(to right bottom, dimgray, black);
}
定義文字樣式:
ul { padding: 0; } li { list-style-type: none; } li span { color: white; font-size: 50px; font-family: monospace; text-transform: uppercase; letter-spacing: 0.1em; }
當滑鼠懸停時,用偽元素繪製傾斜的背景色塊:
li span {
position: relative;
transition: 500ms;
}
li:hover span {
color: #333;
}
li span::before {
content: '';
position: absolute;
height: 100%;
width: 0;
z-index: -1;
transition: 500ms;
}
li:hover span::before {
width: 70%;
transform: rotate(-25deg);
background: white;
}
設定緩動延時,增加動畫效果:
li:hover span {
transition-delay: calc(80ms * var(--n) + 10ms);
}
li:hover span::before {
transition-delay: calc(80ms * var(--n));
}
li span:nth-child(1) {
--n: 1;
}
li span:nth-child(2) {
--n: 2;
}
li span:nth-child(3) {
--n: 3;
}
li span:nth-child(4) {
--n: 4;
}
li span:nth-child(5) {
--n: 5;
}
li span:nth-child(6) {
--n: 6;
}
li span:nth-child(7) {
--n: 7;
}
li span:nth-child(8) {
--n: 8;
}
在單詞左側增加一條滑鼠懸停時變亮的豎線:
li {
padding-left: 2em;
border: 2px solid transparent;
border-left-color: silver;
transition: 500ms;
}
li:hover {
border-left-color: white;
}
dom 中增加幾個按鈕,形成一組按鈕:
<nav>
<ul>
<li>
<span>h</span>
<span>o</span>
<span>m</span>
<span>e</span>
</li>
<li>
<span>p</span>
<span>r</span>
<span>o</span>
<span>d</span>
<span>u</span>
<span>c</span>
<span>t</span>
<span>s</span>
</li>
<li>
<span>s</span>
<span>e</span>
<span>v</span>
<span>i</span>
<span>c</span>
<span>e</span>
<span>s</span>
</li>
<li>
<span>c</span>
<span>o</span>
<span>n</span>
<span>t</span>
<span>a</span>
<span>c</span>
<span>t</span>
</li>
</ul>
</nav>
最後,文字居中對齊,再調整一下按鈕間距:
li {
text-align: center;
margin: 1em 0;
}
大功告成!