【问题标题】:JavaScript changing images with onmouseover and onmouseoutJavaScript 使用 onmouseover 和 onmouseout 改变图像
【发布时间】:2020-03-31 17:56:28
【问题描述】:
我在 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>
【问题讨论】:
标签:
javascript
onmouseover
onmouseout
【解决方案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>
【解决方案2】:
您不需要在 gif 路径的开头使用 /。
替换
document.getElementById("smile").src = "/smiley.gif"
和
document.getElementById("smile").src = "smiley.gif"
sing.gif 也一样