如何使用 CSS 更改滑鼠懸停時的影像?


要使用 CSS 更改滑鼠懸停時的影像,我們將使用 :hover 偽類。在本文中,我們討論了兩種不同的方法來使用 CSS 屬性更改滑鼠懸停時的影像。

我們的 HTML 文件中有一張影像,我們的任務是在將滑鼠懸停在影像上時更改影像。

更改滑鼠懸停時影像的方法

以下是本文將討論的使用 CSS 更改滑鼠懸停時影像的方法列表,其中包含分步說明和完整的示例程式碼。

使用 background 屬性更改滑鼠懸停時的影像

為了使用 CSS 更改滑鼠懸停時的影像,我們使用了 background 屬性和 :hover 偽類。

  • 我們使用了 **container** 類來將影像的 div 內容放置在中心,使用 flexjustify-content 屬性。
  • 然後,在第二步中,我們使用 **card** 類使用 **background** 屬性插入影像,並使用 CSS heightwidth 屬性設定其尺寸。
  • 最後一步,我們使用了 **".card:hover"**,它在滑鼠懸停在第二步中插入的影像上時更改影像。

示例

這是一個完整的示例程式碼,實現了上述步驟,使用 **background** 屬性使用 CSS 更改滑鼠懸停時的影像。

<html>
<head>
   <title>
      To change image on hover with CSS
   </title>
   <style>
      .container {
         display: flex;
         justify-content: center;
      }
      .card {
         width: 350px;
         height: 195px;
         background:url("/plsql/images/plsql-mini-logo.jpg") 
                    no-repeat;
         display: inline-block;
      }
      .card:hover {
         background:
            url("/html/images/test.png") no-repeat;
      }
   </style>
</head>
<body>
   <h3>
      Changing Image On Hover With CSS
   </h3>
   <p>
      In this example we have used CSS <strong>
      :hover</strong> psuedo-class with 
      <strong>background</strong> property to 
      change image on hover with CSS.
   </p>
   <div class="container">
      <div class="card"></div>
   </div>
</body>
</html>

使用 content 屬性更改滑鼠懸停時的影像

在這種使用 CSS 更改滑鼠懸停時影像的方法中,我們使用了 CSS content 屬性和 :hover 偽類,該偽類在滑鼠懸停在影像上時將其作為目標。

  • 我們使用了 **container** 類來將影像的 div 內容放置在中心,使用 flex 和 justify-content 屬性。
  • 然後,在第二步中,我們使用 **card** 類使用 **content** 屬性插入影像。
  • 最後一步,我們使用了 **".card:hover"**,它使用 CSS **content** 屬性更改滑鼠懸停在影像上時的影像。

示例

這是一個完整的示例程式碼,實現了上述步驟,使用 **content** 屬性使用 CSS 更改滑鼠懸停時的影像。

<html>
<head>
   <title>
      To change image on hover with CSS
   </title>
   <style>
      .container {
         display: flex;
         justify-content: center;
      }
      .card {
         content:url("/plsql/images/plsql-mini-logo.jpg");
      }
      .card:hover{
         content:
            url("/html/images/test.png");
      }
   </style>
</head>
<body>
   <h3>
      Changing Image On Hover With CSS
   </h3>
   <p>
      In this example we have used CSS <strong>
      :hover</strong> psuedo-class with 
      <strong>content</strong> property to 
      change image on hover with CSS.
   </p>
   <div class="container">
      <div class="card"></div>
   </div>
</body>
</html>

結論

在本文中,我們瞭解瞭如何使用 CSS 更改滑鼠懸停時的影像。我們討論了兩種不同的方法來使用 CSS 更改滑鼠懸停時的影像:使用 **background** 屬性以及 **:hover** 偽類,以及使用 **content** 屬性。我們可以使用以上兩種方法中的任何一種。

更新於:2024年8月28日

2萬+ 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.