我尝试使用javascript将鼠标悬停在上来更改背景img。
但是javascript仅在第一个
上有效
document.getElementById("a").addEventListener("mouseover", function() {
document.getElementById("bg").style.backgroundImage = "url(https://www.gravatar.com/avatar/9385da4a3618cdc385bd49fe3d951b78?s=32&d=identicon&r=PG)";
}, false);
document.getElementById("a").addEventListener("mouseout", function() {
document.getElementById("bg").style.backgroundImage = "";
}, false);
document.getElementById("b").addEventListener("mouseover", function() {
document.getElementById("bg").style.backgroundImage = "url(https://image.ibb.co/nOtP2U/2.png)";
}, false);
document.getElementById("b").addEventListener("mouseout", function() {
document.getElementById("bg").style.backgroundImage = "";
}, false);
#bg {
width: 100px;
height: 100px;
background-image: url(https://www.gravatar.com/avatar/d5d2cf334288dd34914b29fd5d941e56?s=32&d=identicon&r=PG)
}
<a id="a" href="" > A</a>
<br></br>
<a id="b" href="" > B</a>
<br></br>
<a id="c" href="" > C</a>
<div id="bg"></div>
Sample(或在摘要中查看)
答案 0 :(得分:3)
您的代码存在一些关键问题。例如:
document.getElementById("a").addEventListener("mouseout", function() {
document.getElementBy####Id("bg").style.backgroundImage= //Should be getElementById, not getElementBy####Id
"";
}, false);
此外,输入内容过快还有一些小问题。我对其进行了更改,并且它起作用了。希望这会有所帮助!
答案 1 :(得分:3)
您的问题出在语法上。快速浏览控制台可以向您显示代码出错。
Build Settings -> Headers -> Public
不是有效的方法,相反,您需要使用getElementByI9858d
请参阅修改后的代码:
getElementById
document.getElementById("a").addEventListener("mouseover", function() {
document.getElementById("bg").style.backgroundImage =
"url(https://www.gravatar.com/avatar/9385da4a3618cdc385bd49fe3d951b78?s=32&d=identicon&r=PG)";
}, false);
document.getElementById("a").addEventListener("mouseout", function() {
document.getElementById("bg").style.backgroundImage =
"";
}, false);
document.getElementById("b").addEventListener("mouseover", function() {
document.getElementById("bg").style.backgroundImage =
"url(https://image.ibb.co/nOtP2U/2.png)";
}, false);
document.getElementById("b").addEventListener("mouseout", function() {
document.getElementById("bg").style.backgroundImage =
"";
}, false);
#bg {
width: 100px;
height: 100px;
background-image: url(https://www.gravatar.com/avatar/d5d2cf334288dd34914b29fd5d941e56?s=32&d=identicon&r=PG)
}
答案 2 :(得分:0)
从您的代码中替换
getElementByI9858d("a").addEventListener("mouseout",
到
getElementById("a").addEventListener("mouseout",
在“ mouseout”事件中,您都可以获得所需的结果。