本文章介紹了CSS3之transition實現下劃線的示例代碼,分享給大家,具體如下:
在這里先看看我們的demo

認識transition
這是CSS3中新增的一個樣式,可以實現動畫的過度。通常使用在添加某種效果可以從一種樣式轉變到另一個的時候。
transition屬性
transition: width 1s linear 2s; /*簡寫實例*/
| /*等同如下*/transition-property: width;transition-duration: 1s;transition-timing-function: linear;transition-delay: 2s; | 
tranform屬性
translate() 根據左(X軸)和頂部(Y軸)位置給定的參數,從當前元素位置移動。 rotate() 在一個給定度數順時針旋轉的元素。負值是允許的,這樣是元素逆時針旋轉。 scale() 該元素增加或減少的大小,取決于寬度(X軸)和高度(Y軸)的參數: skew() 包含兩個參數值,分別表示X軸和Y軸傾斜的角度,如果第二個參數為空,則默認為0,參數為負表示向相反方向傾斜。 matrix() matrix 方法有六個參數,包含旋轉,縮放,移動(平移)和傾斜功能。實現我們需要的效果
當然,在這就直接放出代碼,代碼中有注釋方便理解
| /*css代碼*/h2{ position: relative; padding: 15px; text-align: center; }button{ width: 100px; height: 40px; border-radius: 15px; border: none; background: #188FF7; color: #fff; outline: none; cursor: pointer; font-weight: bold;}button:hover{ background: #188EA7;}.container{ width: 600px; display: flex; flex-direction: column; align-items: center; margin: 0 auto; }.line{ position: absolute; left: 0; bottom: 0; height: 3px; width: 100%; transition: transform .5s; background: #188EA7; color: #188EA7; transform: scaleX(0); z-index: 1111; }@keyframes changeColor1{ from{ color: #000; } to{ color: #188EA7; }}@keyframes changeColor2{ from{ color: #188EA7; } to{ color: #000; }}<!--html代碼--><div class="container"> <h2 id="title"> 百度前端學院 <i class="line" id="line"></i> </h2> <button id="change">Change</button></div>//js部分代碼(function () { let btn = document.getElementById('change'); let h2 = document.getElementById('title'); let line = document.getElementById('line'); let count = 0; btn.onclick = function () { if(count%2===0){ line.style.transform = "scaleX(1)"; h2.style.animation = "changeColor1 1s"; h2.style.color = "#188EA7"; count++; }else{ line.style.transform = "scaleX(0)"; h2.style.animation = "changeColor2 1s"; h2.style.color = "#000"; count++; } }})(); |