gpt4 book ai didi

javascript - 使用javascript悬停时更改图像

转载 作者:太空宇宙 更新时间:2023-11-03 23:00:43 25 4
gpt4 key购买 nike

标题。

当使用 IMG 元素时,我已经看到了很多方法:

<img src="blah" id="get" onmouseover="newImage()" onmouseout="oldImage()

Java脚本

function newImage() { document.getElementById(get").src="blah2"}
function oldImage() { document.getElementById("get").src="blah"}

但我在 CSS 上将我的图像作为 background-image: url() 放在一个 id 中:

<div id="image"

我如何应用相同的原则,但是当图像在 CSS 上并且它在 div id

上时

JavaScript 新手请不要框架。

最佳答案

你不需要 JavaScript(但我在下面给出了 JavaScript 的替代方案),只需使用 CSS 的 :hover 伪类。

#get {
background-image: url(/path/to/image/when/not/hovering.png);
}
#get:hover {
background-image: url(/path/to/image/when/hovering.png);
}

示例:此 div 正常显示您的用户图标,然后在您悬停它时显示我的图标:

#get {
width: 50px;
height: 50px;
background-image: url(https://graph.facebook.com/950389301719024/picture?type=small);
}
#get:hover {
background-image: url(https://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=50&d=identicon&r=PG
);
}
<div id="get"></div>

但是如果你真的使用 JavaScript,它与你引用的代码非常相似,你只需更改元素上的 .style.backgroundImage 而不是更改.src:

function startHover(element) {
element.style.backgroundImage = "url(https://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=50&d=identicon&r=PG)";
}
function stopHover(element) {
element.style.backgroundImage = "url(https://graph.facebook.com/950389301719024/picture?type=small)";
}
#get {
width: 50px;
height: 50px;
}
<div id="get" style="background-image: url(https://graph.facebook.com/950389301719024/picture?type=small)" onmouseover="startHover(this)" onmouseout="stopHover(this)"></div>

但我不鼓励使用 onxyz 属性;改为使用现代事件处理:

(function() {
var div = document.getElementById("get");
div.addEventListener("mouseover", function() {
div.style.backgroundImage = "url(https://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=50&d=identicon&r=PG)";
}, false);
div.addEventListener("mouseout", function() {
div.style.backgroundImage = "url(https://graph.facebook.com/950389301719024/picture?type=small)";
}, false);
})();
#get {
width: 50px;
height: 50px;
}
<div id="get" style="background-image: url(https://graph.facebook.com/950389301719024/picture?type=small)"></div>

它使用 addEventListener,所有现代浏览器都支持它(IE8 或 IE9-IE11 在其损坏的“兼容”模式下不支持)。如果您需要支持这些,this answer有一个函数,您可以在没有库的情况下用于跨浏览器事件处理。

关于javascript - 使用javascript悬停时更改图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36661816/

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