使用 CSS 設定懸停效果的速度
要使用 CSS 設定懸停效果的速度,我們將使用兩種不同的方法。這些方法包括使用 CSS 過渡 和 CSS 動畫 屬性。
我們有一個 按鈕 和一個 div 元素,它們在懸停時會更改樣式。我們的任務是使用 CSS 設定 懸停 效果的速度。
使用 CSS 設定懸停效果速度的方法
以下是使用 CSS 設定懸停效果速度的方法列表,我們將在本文中逐步解釋並提供完整的示例程式碼。
使用 transition 屬性設定速度
為了設定懸停效果的速度,我們使用了 CSS 的 transition-duration 屬性。
- 我們使用 btn 類使用 background-color、border、text-align、color、padding、border-radius 和 font-size 為按鈕設定樣式,這設定了按鈕的初始外觀。
- 我們使用 .btn:hover 類在懸停後更改按鈕的外觀。
- 我們使用了 'transition-duration: 1s;' 屬性,它更改了懸停效果的速度。
示例
這是一個完整的示例程式碼,實現了上述步驟,以使用 CSS 設定懸停效果的速度。
<!DOCTYPE html> <html> <head> <title> Set the speed of the hover effect with CSS </title> <style> .btn { background-color: yellow; color: black; text-align: center; font-size: 15px; padding: 20px; border-radius: 15px; border: 3px dashed rgb(38, 2, 45); transition-duration: 1s; } .btn:hover { background-color: #04af2f; color: white; border: 3px solid rgb(38, 2, 45); } </style> </head> <body> <h3> Set the speed of the hover effect with CSS </h3> <p> In this example we have used CSS transition- duration property to Set the speed of the hover effect with CSS. </p> <h4>Hover over this button to see the effect.</h4> <button class = "btn">Result</button> </body> </html>
使用 animation 屬性設定速度
在這種方法中,我們使用了 CSS 的 animation-duration 屬性來設定懸停效果的速度。
- 我們使用 div 標籤建立了一個框,類名為 box。
- 我們使用 box 類使用 CSS 的 height、width 和 background-color 屬性為框設定樣式。
- 我們使用 '@keyframes speed' 為初始、50% 和 100% 設定動畫。
- 我們使用 box:hover 類在懸停時設定動畫效果,它定義了 animation-name 和 animation-timing-function。
- 我們使用了 'animation-duration: 0.9s;' 屬性,它設定了懸停效果的速度。
示例
這是一個完整的示例程式碼,實現了上述步驟,以使用 CSS 設定懸停效果的速度。
<!DOCTYPE html> <html lang="en"> <head> <title> Set the speed of the hover effect with CSS </title> <style> .box { width: 100px; height: 100px; background-color: rgb(38, 2, 45); } @keyframes speed { 0% { width: 100px; height: 100px; background-color: rgb(38, 2, 45); } 50% { width: 150px; height: 150px; background-color: rgb(156, 141, 252); } 100% { width: 200px; height: 200px; background-color: #04af2f; } } .box:hover { animation: speed ease forwards; animation-duration: 0.9s; } </style> </head> <body> <h3> Set the speed of the hover effect with CSS </h3> <p> In this example we have used CSS animation- duration property to Set the speed of the hover effect with CSS. </p> <div class="box"></div> </body> </html>
結論
在本文中,我們討論並理解了兩種使用 CSS 的 transition-duration 和 animation-duration 屬性來設定懸停效果速度的方法。
廣告