2012-04-07 97 views
0

我在div中有圖像,我希望使用jQuery將段落顯示在鼠標懸停的頂部。段落最初是隱藏的。在圖像上顯示段落mouseover

我試過以下方法,但不能讓該段落只在我將鼠標懸停在一張圖片上時,纔會出現在該圖片上。

HTML:

<div id="photos"> 

    <div class="test"> 
     <img src="http://www.blset.com/img/300x200/biostat300200.jpg" /> 
     <p class="desc">Test 1</p> 
    </div> 

    <div class="test"> 
     <img src="http://www.blset.com/img/300x200/barometre1300200.jpg" /> 
     <p class="desc">Test 2</p> 
    </div> 
</div> 

CSS:

#photos {position:relative;width:100%;height:100%;background:#ccc;} 

#photos img {float:left;height:120px;} 

#photos p {display:none; position:absolute;top:0;left:0;} 

的jQuery:

$(".test img").hover(function() { 

     $(".test p").fadeIn(200); 
    }, function() { 

     $(".test p").fadeOut(200); 

    }); 

的jsfiddle:http://jsfiddle.net/m7zFb/13/

回答

1

試試這個:

$(".test img").hover(function(e) { 
    $(e.target).next().fadeIn(200); 
}, function (e) { 
    $(e.target).next().fadeOut(200); 
}); 

與下面的CSS:

.test { float: left;position: relative; } 

#photos {position:relative;} 

#photos img {height:120px;} 

#photos p {display:none; position:absolute;top:0;left:;} 

的jsfiddle:

+0

非常感謝你,這個伎倆。我現在要閱讀關於next()和e.target的更多信息。 – Chris 2012-04-07 01:45:27

+0

當然 - 還有一個注意事項,你可以使用'$(this)'代替'$(e.target)' - 我只是習慣於使用'e.target' ... – 2012-04-07 01:46:19

0

這看起來像你有問題,因爲像P擋的元素沒有得到包含在以這種方式設置時在DIV元素中。此外,你有你的P元素設置爲絕對定位,但尚未定義你的包含元素的位置。所以,你的P結束了相對於視口的定位。個人而言,如果您希望文字位於圖片的頂部並使其更簡單一點:我會將圖片作爲div的背景,使背景圖像:url('imagepath') ;然後,您可以在其中放置文本,除非您確實需要它們,否則不需要P元素標記,因爲您可以在CSS中指定DIV本身的文本位置而不影響IMG元素。

如果你想了解更多關於定位和浮動和塊元素的信息,這是關於這個主題的一個很好的教程:http://coding.smashingmagazine.com/2007/05/01/css-float-theory-things-you-should-know/。請記住,如果您要浮動元素,請始終設置寬度和高度。

+0

感謝您的額外評論@ matthewnreid,我會去讀更多關於它。 – Chris 2012-04-11 17:32:00