2012-12-07 33 views
2

我有一個圖像覆蓋DIV顯示2圖像時,我懸停在圖像上,這工作正常,但我希望它是動態的,併爲頁面上的無數圖像工作,目前它的作品僅用於第一張照片,我對javascript和jquery不太好,並希望得到您的幫助。動態圖像疊加與Jquery

jQuery代碼:

$("#imageOverlay").hover(
    function() { 
     $(this).children("img").fadeTo(200, 0.7).end().children("#hover").show(); 
    }, 
    function() { 
     $(this).children("img").fadeTo(200, 1).end().children("#hover").hide(); 
}); 

HTML代碼:

<div id="imageOverlay"> 
    <div id="hover"> 
    <a href="#"><img src="http://placehold.it/100x30&text=Full View" /></a> 
    <a href="#1"><img src="http://placehold.it/100x30&text=Similar" /></a> 
    </div> 
    <img src="http://placehold.it/1000x1000&text=Thumbnail"> 
</div> 

CSS代碼:

#imageOverlay { 
    display: inline; 
    position: relative; 
} 
#imageOverlay #hover { 
    display: none; 
    position: absolute; 
    margin-top: 10px; 
    margin-right: 10px; 
    z-index: 2; 
} 
#imageOverlay #hover a { 
    width: 100px; 
    height: 30px; 
    display: block; 
    margin-bottom: 5px; 
} 

回答

3

使用和#hover一類,你只能有一個ID的一個實例,因此,當你有多個這樣的ID時,該功能只能找到第一個。此外,只是淡化容器盒,而不是每個單獨的圖像。另外,在動畫之前使用stop(),以確保在人們進行鼠標移動時不會出現奇怪的行爲。然後,首先放置主圖像,確保懸停圖像「在上面」,而不必擔心z-index

HTML

<div class="imageOverlay"> 
    <img src="http://placehold.it/1000x1000&text=Thumbnail"> 
    <div class="hover"> 
    <a href="#"><img src="http://placehold.it/100x30&text=Full View" /></a> 
    <a href="#1"><img src="http://placehold.it/100x30&text=Similar" /></a> 
    </div> 
</div> 

JS

//fade out the images initially 
$(".imageOverlay .hover").fadeTo(0, 0) 
$(".imageOverlay").hover(
    function() { 
     $(this).find(".hover").stop().fadeTo(200, 1); 
    }, 
    function() { 
     $(this).find(".hover").stop().fadeTo(200, 0); 
    } //when writing clean code, be sure your closer ends at the same indent as your opener 
); 

CSS

.imageOverlay { 
    display: inline-block; 
    position: relative; 
} 
.imageOverlay .hover { 
    position: absolute; 
    top: 10px; 
    right: 10px; 
} 
.imageOverlay .hover a { 
    width: 100px; 
    height: 30px; 
    display: block; 
    margin-bottom: 5px; 
} 

而且你的圖像應該出現在頂部時你盤旋!

+0

謝謝:)非常好的描述。 –

+0

不客氣,很高興幫助! –

2

#imageOverlay一個類,並將其應用於您的html中的多個屬性。

CSS:

.imageOverlay 
    //css rules 

的jQuery:

$(".imageOverlay").hover(
    function() { 
     $(this).children("img").fadeTo(200, 0.7).end().children("#hover").show(); 
    }, 
    function() { 
     $(this).children("img").fadeTo(200, 1).end().children("#hover").hide(); 
});  

HTML:

<div class="imageOverlay"> 
    // do stuff 
</div> 
<div class="imageOverlay"> 
    // do stuff 
</div> 
+0

謝謝,這是正確的,但我選擇了蘭迪的答案,其中有更多的細節:) –