簡體   English   中英

在鼠標懸停時,在 JavaScript 中更改圖片

[英]On mouse hover, change picture in JavaScript

我的 HTML 代碼中有一個圖像,我想讓它當我的鼠標懸停在圖像上時,它會變成另一個圖像,當鼠標沒有懸停在圖像上時,它會切換回默認。 我如何在<script>標簽中編程?

不需要<script>標簽。 使用onmouseoveronmouseout更改圖像源。

鼠標移到圖像上時, onmouseover將執行一個動作。 在這種情況下,我們使用this.src將圖像 src 設置為另一個圖像。

onmouseout將在您的鼠標移出圖像時執行一個動作。 在這種情況下,我們再次使用this.src將圖像設置為默認圖像。

 <img title="Hello" src="https://static.independent.co.uk/s3fs-public/thumbnails/image/2017/09/12/11/naturo-monkey-selfie.jpg?w968h681" onmouseover="this.src='https://www.ctvnews.ca/polopoly_fs/1.4037876!/httpImage/image.jpg_gen/derivatives/landscape_1020/image.jpg'" onmouseout="this.src='https://static.independent.co.uk/s3fs-public/thumbnails/image/2017/09/12/11/naturo-monkey-selfie.jpg?w968h681'" />

您可以為此使用 css,例如:

.react {

  background: url('../img/React_Monoo.png');
}

.react:hover {
  background: url('../img/React_Colored.png');
}

這里反應是一個類名

var image = document.getElementById("image");

//Now, we need to add an Event Listener to listen when the image gets mouse over.

image.addEventListener('mouseover', function(){
  image.src = "path/to/newimage"
})
image.addEventListener('mouseout', function(){
    image.src = "path/to/otherimage"
  })

為此,您可以使用 on mouse out。 這是我的工作。

<html>
<head>
</head>

<body>
 <script>

 function setnewimage() {
 document.getElementById("img2").src = "myquiz1.png";
 }
 function setnewimage1() {
 document.getElementById("img2").src = "myquiz2.png";
 }
 function setnewimage2() {
 document.getElementById("img2").src = "myquiz3.png";
 }
 function setnewimage3() {
 document.getElementById("img2").src = "pic33.png";
 }
 function setoldimage() {
 document.getElementById("img2").src = "myquiz1.png";
 }
 </script>
 <div>
 <img id="img2" src="" width="300">
 <br>
 <img id="img1" src="myquiz1.PNG" onmouseover="setnewimage()"
width="300" onmouseout="setoldimage()">
 <img id="img66" src="myquiz2.PNG" onmouseover="setnewimage1()"
width="300" height="200" onmouseout="setoldimage()">
 <img id="img87" src="myquiz3.PNG" onmouseover="setnewimage2()"
width="300" height="200" onmouseout="setoldimage()">
 <img id="img80" src="pic33.PNG" onmouseover="setnewimage3()"
width="300" height="200" onmouseout="setoldimage()">
 </div>
</body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM