使用 CSS 設定懸停效果的速度


要使用 CSS 設定懸停效果的速度,我們將採用兩種不同的方法。這些方法包括使用 CSS transitionCSS animation 屬性。

我們有一個 按鈕 和一個 div 元素,它們在懸停時會更改樣式。我們的任務是使用 CSS 設定 懸停 效果的速度。

使用 CSS 設定懸停效果速度的方法

以下是使用 CSS 設定懸停效果速度的方法列表,我們將在本文中逐步講解並提供完整的示例程式碼。

使用 transition 屬性設定速度

為了設定懸停效果的速度,我們使用了 CSS transition-duration 屬性。

示例

這是一個完整的示例程式碼,實現了上述步驟,以使用 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 heightwidth 和 background-color 屬性來設定盒子的樣式。
  • 我們使用 '@keyframes speed' 設定了初始、50% 和 100% 的動畫。
  • 我們使用了 box:hover 類來設定懸停時的動畫效果,它定義了 animation-nameanimation-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-durationanimation-duration 屬性來設定 CSS 懸停效果速度的兩種方法。

更新於:2024年8月6日

13K+ 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告