JavaScript使用onmouseover和onmouseout更改图像

时间:2020-03-31 17:56:28

标签: javascript onmouseover onmouseout

我已经在Stack Overflow上找到了类似的问题和答案,但我无法开始工作。当页面加载时,一切都可以找到,但是当我将鼠标悬停在页面上时,不会显示新的gif。

在浏览器中检查代码时,似乎在两个图像之间切换。

<!DOCTYPE html>
<html>
<head>
<script>


function normalImg() {
  document.getElementById("smile").src = "/smiley.gif"
}
function singing() {
  document.getElementById("smile").src = "/sing.gif"
}

</script>
</head>
<body>


<img onmouseout="normalImg()" border="0" src="smiley.gif" alt="Smiley" width="32" height="32" id="smile" 
onmouseover="singing()" border="0" src="sing.gif" alt="singing" width="32" height="32">


<p>onmouse out and onmouseover changing images</p>

</body>
</html>

3 个答案:

答案 0 :(得分:1)

您应该在标签内只有一个src属性,您可以尝试以下代码:

<!DOCTYPE html>
<html>
<head>
<script>


function singing() {
  document.getElementById("smile").src = "https://upload.wikimedia.org/wikipedia/commons/0/06/180717_%EC%97%B4%EB%A6%B0%EC%9D%8C%EC%95%85%ED%9A%8C_%ED%8A%B8%EC%99%80%EC%9D%B4%EC%8A%A4_%2818%29.jpg"
  document.getElementById("smile").alt="smiling"
}

function crying() {
  document.getElementById("smile").src = "https://upload.wikimedia.org/wikipedia/commons/c/cd/Chou_Tzuyu_at_the_Golden_Disc_Awards_2019.png"
  document.getElementById("smile").alt="crying"
}

</script>
</head>
<body>


<img onmouseover="singing()" onmouseout="crying()" src="https://upload.wikimedia.org/wikipedia/commons/c/cd/Chou_Tzuyu_at_the_Golden_Disc_Awards_2019.png" alt="singing" width="100" height="100" id="smile">


<p>onmouse out and onmouseover changing images</p>

</body>
</html>

答案 1 :(得分:0)

您到达gif的路径的开头不需要const url: string = 'your-url.example'; try { const response = await axios.get(yourUrl); } catch (exception) { process.stderr.write(`ERROR received from ${url}: ${exception}\n`); }

替换 /document.getElementById("smile").src = "/smiley.gif"

与sing.gif相同

答案 2 :(得分:0)

与其在悬停和悬停时使用JavaScript来更改图像源,不如仅在悬停时更改图像源就更好。

检查一下: CSS: Change image src on img:hover

  • 悬停可同时处理mouseenter事件和mouseleave事件。

  • 鼠标悬停最适合以下情况:您只在乎鼠标将边框越过一个元素,而实际上却不在意它离开时会发生什么。如果要在元素上触发某些事件。

相关问题