2013-12-16 62 views
0

我有一個圖像,我希望它在鼠標懸停在圖像上時更改其來源。它不適用於我目前的代碼。當鼠標懸停在圖像上時,圖像不會變成另一幅圖像?

#logo { 
height: 15em; 
width: 15em; 
margin-left: auto; 
margin-right: auto; 
margin-top: -2.5em 
} 

#logo:hover { 
content: url('C:\Users\haines\Desktop\Logo Hover.png'); 
height: 15em; 
width: 15em; 
margin-left: auto; 
margin-right: auto; 
margin-top: -2.5em 
} 

和HTML代碼:

<img id = "logo" src = "C:\Users\haines\Desktop\Logo.png" />

+1

您不能更改使用CSS的'img'元素的'src'。你可以使用Javascript來做到這一點,或使用背景圖片而不是'img'(如果你的圖片是內容而不是裝飾品,那麼你必須使用Javascript來解決你的問題,這將是一個壞主意)。 – kapa

回答

0

你必須使用一個背景圖像標誌在它改變時,懸停。不要在html中使用img標籤來設置第一個日誌img。

#logo { 
    content: url("C:\Users\haines\Desktop\Logo.png"); 
} 

此外,而不是內容,我會使用的背景下,像這樣

#logo { 
    background: url("C:\Users\haines\Desktop\Logo.png"); 
} 

,並同樣爲您#logo:懸停

0

使用圖像標籤也許不是最好的風格去做這個。我會推薦這樣的東西。 在HTML文件中

<div class="myImage"></div> 

,並在你的CSS文件,你可以使用這個

.myImage { background: url(images/logo.png); width: 200px; height: 200px;} 
.myImage:hover { background: url(images/logoHoverState.png); } 

,你應該使用,而不是引用到IDS類。這使您的代碼更可回收。

0

也許你可以切換懸停時的src值,如果你想在一個img標籤的標誌。 。 。

的JavaScript/jQuery的

var LogoSwap = function() { 
    var $this = $(this); 
    var new = $this.data('hover'); 
    $this.data('hover', $this.attr('src')); 
    $this.attr('src', new); 
} 

$(function() { 
    $('img#logo').hover(LogoSwap, LogoSwap); 
}); 

HTML

<img id="logo" src="C:\Users\haines\Desktop\Logo.png" data-hover="C:\Users\haines\Desktop\LogoHover.png" /> 
0

你不能直接與只是HTML和CSS改變圖像的來源。但有幾種不同的方法來創建一個適合您的需要的簡單圖像翻轉:

1:如果您將圖像包裝在div中,然後讓圖像在懸停時顯示消失,則可以做到這一點背景圖片:

HTML:

<div class="image"> 
    <img src="http://placehold.it/250/ffffff/000000"> 
    </div> 

CSS:

.image { 
    width: 250px; 
height: 250px; 
    background: url('http://placehold.it/250/000000/ffffff'); 
} 
.image:hover img { 
    display: none; 
} 

2:如果背景的做法是可行的,然後只是換背景圖像可能是一個解決辦法:

HTML:

<div class="image"></div> 

CSS:

.image { 
width: 250px; 
height: 250px; 
background: url('http://placehold.it/250/000000/ffffff'); 
} 
.image:hover { 
background: url('http://placehold.it/250/000000/ffffff'); 
http://placehold.it/250/ffffff/000000 
} 

3:如果你堅持直接改變圖像的來源,我建議尋找一種簡單的JavaScript方法:

HT ML:

<img src="http://placehold.it/250/ffffff/000000" onmouseover="hover(this);" onmouseout="unhover(this);"> 

JS:

function hover(element) { 
element.setAttribute('src', 'http://placehold.it/250/000000/ffffff'); 
} 
function unhover(element) { 
element.setAttribute('src', 'http://placehold.it/250/ffffff/000000'); 
}