只针对一个div .on()悬停,而不是全部 - Jquery

时间:2013-04-22 10:51:31

标签: jquery

我目前正在使用该代码在图像的鼠标中心将不透明度设置为1,并在mouseleave上再次返回0。它不是显示一个图像,而是在悬停时显示所有图像。

我已尝试使用(this)代替(.project-hover img),因此它仅影响该特定div,但我需要定位(.project-hover img)而不是.span4从...开始。

我将如何实现这一目标?

$(document).ready(function() {
    $(".span4").on("mouseenter", function() {
        $('.project-hover img').stop();//halts previous animation if it's running
        $('.project-hover img').animate({
            opacity: 1
        });
    }).on("mouseleave", function() {
        $('.project-hover img').stop();
        $('.project-hover img').animate({
            opacity: 0
        });
    });
});

HTML

<div class="span4">
    <div class="wrap-title">
        <div class="position">
            <div class="title"><a href="<?php echo get_permalink(); ?>"><?php the_title();?></a></div>
            <div class="tags"><?php echo $cats; ?> </div>
        </div>
    </div>  
    <div class="project-hover"><img src="<?php echo catch_that_image(); ?>">    </div>
</div>

4 个答案:

答案 0 :(得分:3)

使用find()查看文档... http://api.jquery.com/find/

$(document).ready(function() {
    $(".span4").on("mouseenter", function() {
        $(this).find('.project-hover img').stop();//halts previous animation if it's running
        $(this).find('.project-hover img').animate({
            opacity: 1
        });
    }).on("mouseleave", function() {
        $(this).find('.project-hover img').stop();
        $(this).find('.project-hover img').animate({
           opacity: 0
        });
    });
});

<强>更新

您还应该链接您的方法以提高效率,并且您可能希望将true, true传递给.stop()方法。 (以防止队列iusses)

 $(document).ready(function() {
        $(".span4").on("mouseenter", function() {
            $(this).find('.project-hover img').stop(true, true).animate({
                opacity: 1
            });
        }).on("mouseleave", function() {
            $(this).find('.project-hover img').stop(true, true).animate({
               opacity: 0
            });
        });
    });

答案 1 :(得分:0)

$(".span4").on("mouseenter", function() {
        $('.project-hover img', $(this)).stop();//halts previous animation if it's running
        $('.project-hover img', $(this)).animate({
            opacity: 1
        });
    }).on("mouseleave", function() {
        $('.project-hover img', $(this)).stop();
        $('.project-hover img', $(this)).animate({
           opacity: 0
        });
    });

答案 2 :(得分:0)

this是指用户悬停的当前.span4元素,因此您只需找到其中的目标元素:

$(this).find('.project-hover img').animate(...);

来自documentation

  

当jQuery调用处理程序时,this关键字是对传递事件的元素的引用;对于直接绑定事件,这是附加事件的元素,对于委派事件this是匹配selector的元素。 (请注意,如果事件来自后代元素,则这可能不等于event.target。)要从元素创建jQuery对象以便可以与jQuery方法一起使用,请使用$(this)

DOM遍历方法列表:http://api.jquery.com/category/traversing/tree-traversal/

答案 3 :(得分:0)

有一个我在这里找到的CSS解决方案,任何人都想要这个更简单的替代方案以供将来参考:

css: show div when another div is hover

相关问题