CSS 更改img:hover上的图像src?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (309)

我需要改变<img>源URLhover

HTML

<img id="my-img" src="http://dummyimage.com/100x100/000/fff"/>

CSS

#my-img:hover {
    content: url('http://dummyimage.com/100x100/eb00eb/fff');
}
提问于
用户回答回答于

只有html和CSS,所以不能更改图像的src。如果你确实将img标记替换为div标记,那么你可能可以更改设置为背景的图像,如下所示

div {
    background: url('http://dummyimage.com/100x100/000/fff');
}
div:hover {
    background: url('http://dummyimage.com/100x100/eb00eb/fff');
}

如果你认为可以使用一些javascript代码,那么你应该能够更改img标记的src,如下所示

function hover(element) {
    element.setAttribute('src', 'http://dummyimage.com/100x100/eb00eb/fff');
}
function unhover(element) {
    element.setAttribute('src', 'http://dummyimage.com/100x100/000/fff');
}

而html是

<img id="my-img" src="http://dummyimage.com/100x100/000/fff" onmouseover="hover(this);" onmouseout="unhover(this);" />
用户回答回答于
<a href="#">
<img src="http://icons.iconarchive.com/icons/fasticon/angry-birds/128/yellow-bird-icon.png" 
onmouseover="this.src='http://icons.iconarchive.com/icons/fasticon/angry-birds/128/red-bird-icon.png'"
onmouseout="this.src='http://icons.iconarchive.com/icons/fasticon/angry-birds/128/yellow-bird-icon.png'"
border="0" alt=""/></a>

扫码关注云+社区

领取腾讯云代金券