如何在悬停时更改图像

时间:2013-12-12 03:15:56

标签: javascript html css

我一直在想办法做到这一点,但我还没想出来,所以我想我会问这里!

例如,我有这个:

<a href="index.html"><img src="arrow.png"/>Index</a>

我希望在悬停Index时,图片应该使用CSS更改为arrow_hover.png。

2 个答案:

答案 0 :(得分:1)

使用伪类:hover

首先,给图像一个类,使其不会以每个img为目标。说,hover-image

则...

.hover-image:hover {
    background: url('arrow_hover.png');
}

无论其!这不行!仅使用CSS,您无法更改图像属性src。您需要使用javascript。

您可以将其更改为div而不是img代码,此代码也可以使用。但不是你当前的标记。

要在javascript中执行此操作,请为元素指定id以使事情更轻松。在这种情况下.. derp

你会这样做:

var x = document.getElementById("derp");
x.mouseenter = function() {
    this.src = "arrow_hover.png";
}
x.mouseout = function() {
    this.src = "arrow.png";
}

答案 1 :(得分:0)

您只能使用CSS执行此操作。试试这个CSS:

#theImage {
height:250px; //Or whatever size it needs to be
width:320px; //Or, again, whatever it needs to be
background-image:url(stuff.jpg);
}
#theImage:hover {
background-image:url(otherstuff.jpg);
}

#theImage将成为div。