在图像鼠标悬停上显示段落

时间:2012-04-07 01:26:55

标签: jquery hover onmouseover

我有div中的图像,我想在鼠标悬停时使用jQuery显示段落。这些段落最初是隐藏的。

我尝试过以下操作,但只有在鼠标悬停在一张图片上时才能显示段落,仅在该图片的顶部。

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/

2 个答案:

答案 0 :(得分: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:

答案 1 :(得分:0)

这看起来有问题,因为在以这种方式设置时,像P这样的块元素不会包含在DIV元素中。此外,您已将P元素设置为绝对定位,但尚未定义包含元素的位置。因此,您的P最终会相对于视口定位。

就个人而言,如果你希望文本位于图像的顶部并使其更简单:我会将图像作为div的背景,使background-image:url('imagepath');然后你可以直接在那里填充你的文本,除非你真的需要它们,因为你可以在CSS中指定DIV本身的文本定位,而不会影响IMG元素。

如果您想了解有关定位以及浮动和块元素的更多信息,这是一个关于该主题的优秀教程:http://coding.smashingmagazine.com/2007/05/01/css-float-theory-things-you-should-know/。请记住,如果要浮动元素,请始终设置宽度和高度。

相关问题