連結底線是非常常見的一種樣式,最近做了一個非常簡單的視覺效果,非常不錯,完整代碼查看。
<!DOCTYPE html><html><head> <meta charset="gb2312"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title><style>body{ background-color: #000; } h2{ text-align: center; margin-top: 100px; } h2 > a { position: relative; color: #FFF; text-decoration: none; padding-bottom: 5px; } h2 > a:hover { color: #FFF; } h2 > a:before { content: ""; position: absolute; width: 100%; height: 2px; bottom: 0; left: 0; background-color: #FFF; visibility: hidden; -webkit-transform: scaleX(0); transform: scaleX(0); -webkit-transition: all 0.3s ease-in-out 0s; transition: all 0.3s ease-in-out 0s; } h2 > a:hover:before { visibility: visible; -webkit-transform: scaleX(1); transform: scaleX(1); } </style></head><body> <h2> <a href="/">懸停在我上面</a> </h2></body></html>
建立這種效果是非常簡單的,不需要添加額外的DOM元素到HTML,不過需要考慮一下瀏覽器的相容性問題,在老舊版本的瀏覽器中它只會顯示為一個普通的底線。
好了,現在正式開始。我們需要做的第一件事就是去除text-decoration,並設定連結為相對定位。我們需要確保連結在hover時不會改變顏色,這裡我們拿h2舉例:
h2 > a { position: relative; color: #000; text-decoration: none; } h2 > a:hover { color: #000; }
接下來,我們要添加border,通過變換隱藏它。插入一個:before並且設定它scaleX(0),保守起見,如果瀏覽器不支援,我們通過visibility: hidden隱藏它。
h2 > a:before { content: ""; position: absolute; width: 100%; height: 2px; bottombottom: 0; left: 0; background-color: #000; visibility: hidden; -webkit-transform: scaleX(0); transform: scaleX(0); -webkit-transition: all 0.3s ease-in-out 0s; transition: all 0.3s ease-in-out 0s; }
最後設定動畫時間為0.3s,現在我們只需要設定元素在hover時顯示並且scaleX(1):
h2 > a:hover:before { visibility: visible; -webkit-transform: scaleX(1); transform: scaleX(1); }
大功告成!
這樣就完成了一個很有活力的底線動畫。
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援topic.alibabacloud.com。