文字下劃線效果(標題hover效果)
<!-- html結構 -->
<div>
<a href="javascript:void(0);" class="demo1">自己實現的hover效果</a>
</div>
/* css樣式 */
.demo1{
position: relative;
text-decoration: none;
font-size: 20px;
color: #333;
}
.demo1:before{
content: "";
position: absolute;
left: 50%;
bottom: -2px;
width: 0;
height: 2px;
background: #4285f4;
transition: all .3s;
}
.demo1:hover:before{
width: 100%;
left: 0;
right: 0;
}
關鍵在於沒有hover的時候定義width爲0,這樣可以實現寬度從0到100%的變化。
left爲50%,目的是爲了動畫開始的位置是在50%的位置。
方法二:
<!-- html結構 -->
<div>
<a href="javascript:void(0);" class="demo2">Hexo next主題的實現</a>
</div>
/* css樣式 */
.demo2{
position: relative;
text-decoration: none;
font-size: 20px;
color: #333;
}
.demo2:before{
content: "";
position: absolute;
left: 0;
bottom: -2px;
height: 2px;
width: 100%;
background: #4285f4;
transform: scale(0);
transition: all 0.3s;
}
.demo2:hover:before{
transform: scale(1);
}
這個實現的關鍵就是scale(0)到scale(1)的變化。
CSS3的scale transform的原點是中點,所以會從中間的位置開始動畫。
兩者區別
通過動畫也看出來,next的動畫有透明漸變的效果,和scale的表現形式有關。
第一個實現只是width變化,但是也可以用animation實現和next一樣的效果。