2013-12-12 102 views
1

我一直在想辦法做到這一點,但我還沒有弄清楚,所以我想我會問這裏!

因此,例如,我有這樣的:
如何在懸停時更改圖像

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

我想上徘徊指數,圖像應更改爲arrow_hover.png,使用CSS。

+0

這不可能與CSS。 –

+0

我認爲你可以讓arrow.png成爲背景圖片 – Andrew

+0

可能會有幫助嗎? http://css-tricks.com/forums/topic/show-image-on-hover/ – Jwosty

回答

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"; 
} 
+0

好的,謝謝你的回覆。我將如何在Javascript中做到這一點? – user3068228

+0

爲我更新了我的答案 –

+0

a或圖像是否具有元素? – user3068228

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。