如何使用 CSS 在懸停時新增過渡效果?
要使用 CSS 在懸停時新增過渡效果,首先,使用 :hover 選擇器。在此之下,使用 transform 屬性並縮放元素。對於過渡,使用 transition 屬性。transition 簡寫屬性允許我們在一行中將 transition-property、transition-duration、transition-timing-function 和 transition-delay 作為值指定給 transition 屬性 -
transition-duration - 指定過渡效果完成所需的時間(秒或毫秒)
transition-property - 效果所作用的屬性名稱
transition-timing-function - 過渡的速度曲線
transition-delay - 以秒為單位設定過渡效果的延遲
請記住,您需要設定應用效果的 CSS 屬性以及持續時間。
帶持續時間的過渡
讓我們來看一個在懸停時新增過渡效果的示例。我們使用 transition 簡寫屬性設定了過渡持續時間 -
示例
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; } .scaleBtn { display: inline-block; background-color: #0c1377; border: none; color: white; padding: 16px 32px; text-align: center; font-size: 16px; transition: 0.3s; margin: 20px; } .scaleBtn:hover { transform: scale(1.5); } </style> </head> <body> <h1>Transition on hover example</h1> <button class="scaleBtn">Hover Here</button> </body> </html>
帶時間、持續時間、屬性和延遲的過渡
在這個例子中,我們設定了所有屬性的過渡 -
過渡持續時間
下面,為 border-radius 和 background-color 屬性設定了持續時間。transition-duration 設定為 2 秒 -
2s for the border-radius property 2s for the background-color property
過渡延遲
延遲設定在 border-radius 和 background-color 屬性上。transition-delay 分別設定為 1 秒和 2 秒;
1s for the border-radius property 2s for the background-color property
過渡時間函式
過渡設定在 border-radius 和 background-color 屬性上。transition-timing-function 設定為 -
ease for the border-radius ease-out for the background-color property
示例
讓我們來看一個設定帶時間、持續時間、屬性和延遲的過渡效果的示例。我們設定了 transition 簡寫屬性 -
<!DOCTYPE html> <html> <head> <style> .container div { width: 300px; height: 100px; border-radius: 1px; background-color: rgb(25, 0, 255); border: 2px solid red; transition: border-radius 2s ease 1s, background-color 2s ease-out 1s ; } .container:hover div { background-color: orange; border-radius: 50%; } </style> </head> <body> <h1>Transition shorthand property</h1> <div class="container"> <div></div> </div> <p>Hover over the above div to change its color and its shape to oval</hp> </body> </html>
廣告