使用javascript悬停时更改图像

使用javascript悬停时更改图像,javascript,html,css,Javascript,Html,Css,标题 当使用IMG元素时,我看到了很多方法: <img src="blah" id="get" onmouseover="newImage()" onmouseout="oldImage() 但是我将我的图像作为背景图像:url()保存在CSS上的id中: <div id="image" 您不需要JavaScript(但我在下面给出了一个JavaScript替代方案),只需使用CSS的:hover伪类即可 #get { background-image: url(/pat

标题

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

<img src="blah" id="get" onmouseover="newImage()" onmouseout="oldImage()
但是我将我的图像作为
背景图像:url()
保存在CSS上的id中:

<div id="image"

您不需要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通常显示您的用户图标,如果您将其悬停,则显示我的图标:

#获取{
宽度:50px;
高度:50px;
背景图片:url(https://graph.facebook.com/950389301719024/picture?type=small);
}
#获得:悬停{
背景图片:url(https://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=50&d=identicon&r=PG
);
}

您不需要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通常显示您的用户图标,如果您将其悬停,则显示我的图标:

#获取{
宽度:50px;
高度:50px;
背景图片:url(https://graph.facebook.com/950389301719024/picture?type=small);
}
#获得:悬停{
背景图片:url(https://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=50&d=identicon&r=PG
);
}

好吧,我把它钉死了。但是为了了解如何使用上面的示例作为模板使用javascript?@blueHorse如果你想使用javascript,那么你可以使用两个具有不同背景图像的CSS类。然后将鼠标悬停在元素上,将另一个类添加到元素中。鼠标一出,移除那个类。@BlueHorse:我已经添加了那个类。Rajesh的方法也很好,因为它将图像路径等保存在CSS中,而不是代码中。@T.J.Crowder你是个好人!非常感谢你抽出时间。好的,我搞定了。但是为了了解如何使用上面的示例作为模板使用javascript?@blueHorse如果你想使用javascript,那么你可以使用两个具有不同背景图像的CSS类。然后将鼠标悬停在元素上,将另一个类添加到元素中。鼠标一出,移除那个类。@BlueHorse:我已经添加了那个类。Rajesh的方法也很好,因为它将图像路径等保存在CSS中,而不是代码中。@T.J.Crowder你是个好人!非常感谢您抽出时间。