2016-11-12 92 views
0

我想創建一個java腳本代碼,以便當我將鼠標移到顯示的三個圖像中的一個上時,當前圖像將被替換爲新圖像。 第一:我想爲圖像元素的鼠標輸入事件創建一個事件處理程序。我希望此處理程序更改圖像元素的src屬性,以便它指向翻轉圖像的url。 第二:我必須寫一個鼠標事件。此處理程序應將圖像元素的src屬性返回到原始圖像JavaScript。 Image Rollover

以下是html代碼。

<!DOCTYPE HTML> 
 
<html lang="en"> 
 
<head> 
 
\t <meta charset="utf-8"> 
 
\t <title>Image Rollovers</title> 
 
\t <link rel="stylesheet" href="main.css"> 
 
\t <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> \t 
 
    <script src="rollover.js"></script> 
 
</head> 
 
\t 
 
<body> 
 
\t <section> 
 
\t \t <h1>Ram Tap Combined Test</h1> 
 
\t \t <ul id="image_rollovers"> 
 
\t  \t <li><img src="images/h1.jpg" alt="" id="images/h4.jpg"></li> 
 
\t  \t <li><img src="images/h2.jpg" alt="" id="images/h5.jpg"></li> 
 
\t  \t <li><img src="images/h3.jpg" alt="" id="images/h6.jpg"></li> 
 
\t  </ul>   
 
\t </section> 
 
</body> 
 
</html>

回答

1

這將是清潔用CSS來做到這一點:

#img { 
 
    width: 200px; 
 
    height: 200px; 
 
    border: 1px solid black; 
 
    background-image: url("https://placebear.com/200/200"); 
 
} 
 

 
#img:hover { 
 
    background-image: url("http://placekitten.com/200/200"); 
 
}
<div id="img"></div>

但如果你真的想使用事件偵聽器的方法:

var img = document.querySelector('img'); 
 

 
img.addEventListener('mouseover', function() { 
 
    this.src = "https://placekitten.com/200/200" 
 
}) 
 

 
img.addEventListener('mouseout', function() { 
 
    this.src = "https://placebear.com/200/200" 
 
})
img { 
 
    width: 200px; 
 
    height: 200px; 
 
    border: 1px solid black; 
 
}
<img src="https://placebear.com/200/200">