悬停在文本上打开图像

时间:2012-09-21 22:00:44

标签: javascript jquery html hover

当我将鼠标悬停在单词“PIC”上时,我想打开一张图像,但是我在同一部分中有10个或更多这个&它们中的每一个都必须显示PIC元素的特定图像。

<h6 id="pic1" class="pic"> PIC</h6>
<div id="img_pic1" class="imgpic" style="display:none"><imgsrc="img/image1.jpg"/></div>

<h6 id="pic2" class="pic"> PIC</h6>
<div id="img_pic2" class="imgpic" style="display:none"><img src="img/image2.jpg"/>/div>

<h6 id="pic3" class="pic"> PIC</h6>
<div id="img_pic3" class="imgpic" style="display:none"><img src="img/image3.jpg"/>/div>

ECT .....

<script>
$('h6.pic').mouseenter(function(){
$('div.img_pic').fadeIn();
}).mouseleave(function(){
$('div.img_pic').fadeOut();
});
</script>

这项工作正常,但它打开所有图像而不是只打开我徘徊的PIC的图像? 任何帮助将不胜感激。非常感谢你。

3 个答案:

答案 0 :(得分:1)

试试这个

<script>
   $('h6.pic').mouseenter(function(){
    $(this).next().fadeIn();
       }).mouseleave(function(){
    $(this).next().fadeOut();
    });
</script>

选中此FIDDLE

你也没有正确关闭div

<img src="img/image2.jpg"/>/div>

更新代码

UPDATED FIDDLE

如果是这种情况,那么你可以试试这个

$('h6.pic').mouseenter(function() {
        console.log($(this).next('div'))
        $(this).next().next('.imgpic').fadeIn();
    }).mouseleave(function() {
        $(this).next().next('.imgpic').fadeOut();
    });​

// OR

$('h6.pic').mouseenter(function() {
            console.log($(this).next('div'))
            $(this).next().next().fadeIn();
        }).mouseleave(function() {
            $(this).next().next().fadeOut();
        });​

答案 1 :(得分:1)

你应该使用$(this) - 指当前元素 - 和next() - 当前元素之后的元素

$('h6.pic').mouseenter(function(){
    $(this).next('div.imgpic').fadeIn();
}).mouseleave(function(){
    $(this).next('div.imgpic').fadeOut();
});

您的选择器中也有拼写错误

$('div.img_pic') // <-- your class is imgpic without the _

答案 2 :(得分:0)

恕我直言,使用$(this).next()方法有点不灵活;通过附加指向每个标题元素的目标pic的data-*属性,我会稍微改变它:

<h6 id="pic1" class="pic" data-target="img_pic1"> PIC</h6>
<div id="img_pic1" class="imgpic" style="display:none"><img src="img/image1.jpg"/></div>

<h6 id="pic2" class="pic" data-target="img_pic2"> PIC</h6>
<div id="img_pic2" class="imgpic" style="display:none"><img src="img/image2.jpg"/></div>

<h6 id="pic3" class="pic" data-target="img_pic3"> PIC</h6>
<div id="img_pic3" class="imgpic" style="display:none"><img src="img/image3.jpg"/></div>​

然后你的jQuery看起来像这样:

$('h6.pic').each(function () {
  var target = $(this).data('target');
  $(this).mouseenter(function () {
    $('#' + target).fadeIn();
  }).mouseleave(function () {
    $('#' + target).fadeOut();
  });         
});​

到底是什么,这是fiddle

相关问题