gpt4 book ai didi

javascript - 悬停在一个元素上更改另一个元素的背景图像

转载 作者:搜寻专家 更新时间:2023-10-31 22:36:44 24 4
gpt4 key购买 nike

我尝试使用 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 (或在片段中查看)

最佳答案

您的问题出在语法上。快速查看控制台可以显示您在代码中遇到的错误。

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)
}
<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>

关于javascript - 悬停在一个元素上更改另一个元素的背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52499273/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com