2012-04-07 103 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