首頁  >  文章  >  web前端  >  如何使用 CSS 更改懸停時的圖像?

如何使用 CSS 更改懸停時的圖像?

王林
王林轉載
2023-09-01 10:05:111354瀏覽

如何使用 CSS 更改悬停时的图像?

The "hover" pseudo-class is used to select and apply styles to an HTML element when a user hovers their mouse over it.

Changing an image on hover with CSS is a simple process that can add an extra layer of interactivity to the website. Here, we will learn step-by-step guide to changing an image on hover with CSS −

##Prepare the images

使用CSS在懸停時更改圖像的第一步是擁有您想要使用的兩個圖像:預設圖像和懸停圖像。確保這兩個圖像都保存在您的網站上,並且您知道每個圖像的URL。

將預設影像加入到您的HTML中

使用img標籤並指定影像的來源(src)。例如 -

<img src="如何使用 CSS 更改懸停時的圖像?-image.jpg" alt="如何使用 CSS 更改懸停時的圖像?"> 

在你的CSS中加入一個懸停規則

In the CSS file, we add a rule to change the image on hover. we will do this by targeting the div tag and specifying a :hover pseudo-class. For example −

img:hover {
   content: url("hover-image.jpg");
} 

Example

Here is an example to change the image on hover using CSS.

<html>
<head>
   <title>Change Image on Hover in CSS</title>
   <style>
      body{ 
         text-align:center;
      }
      div {
         width: 250px;
         height: 195px;
         background:
         url("https://www.tutorialspoint.com/dip/images/black_and_white.jpg") norepeat;
         display: inline-block;
      }
      div:hover {
         background:
         url("https://www.tutorialspoint.com/dip/images/einstein.jpg") no-repeat;
      }
   </style>
</head>
<body>
   <h2>Change Image on Hover Using CSS</h2>
   <div class="card"></div>
</body>
</html>

Conclusion

使用CSS在懸停時更改圖像是一種簡單而有效的方式,可以為網站增加額外的參與度。這是一個很好的方式來為用戶創建互動體驗,可以幫助他們更長時間地停留在網站上,提高他們的整體滿意度。

以上是如何使用 CSS 更改懸停時的圖像?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除