在悬停时使用fadeTo的Jquery问题

时间:2011-12-15 20:51:46

标签: jquery html fadeto

所以基本上我试图让div.show在悬停时淡入,然后当你停止悬停时,让它渐渐恢复到0的不透明度。

然而,当你停止盘旋时,我无法让div淡出0。

这是我的代码:

$(document).ready(function(){
    $("div.post.photo").live('hover', function() {
        $(this).children("div.show").fadeTo("slow", .7);
    }, function(){
        $(this).children("div.show").fadeTo("slow", 0);
    });
});

谢谢

4 个答案:

答案 0 :(得分:2)

您需要使用mouseenter明确检查mouseleaveevent.type个事件。您不应该将它们绑定两次。

$(document).ready(function(){
    $("div.post.photo").live('hover', function(event) {

        if( event.type === 'mouseenter') 
            $(this).children("div.show").fadeTo("slow", .7);
        else if( event.type === 'mouseleave' )
            $(this).children("div.show").fadeTo("slow", 0);
    });
});

这是一个fiddle。我个人会使用.on,但我不确定你使用的是什么版本的jQuery。

答案 1 :(得分:1)

我很确定你应该把它淡化回1而不是0。 另外live()只需要一个处理程序。您需要单独添加鼠标输出事件。

fiddle

答案 2 :(得分:1)

我发现如果您使用.hover()而不是.live(),这是有效的,所以我认为问题是.live()不支持悬停事件,可能是因为{{1}只有一个处理函数,而不是两个。

在jQuery 1.7+中,这似乎有效(将其分解为两个事件处理程序并现代化为.live()):

.on()

你可以在这里看到它:http://jsfiddle.net/jfriend00/YV2nU/

仅供参考,我切换到$(document).ready(function(){ $(document.body).on("mouseenter", "div.post.photo", function() { $(this).children("div.show").fadeTo("slow", .7); } ); $(document.body).on("mouseleave", "div.post.photo", function() { $(this).children("div.show").fadeTo("slow", .0); } ); }); ,因为jQuery 1.7 +中不推荐使用.on()

答案 3 :(得分:0)

您的问题是hover不是Javascript事件,它是mouseentermouseleave事件的JQuery简写,因此无法在{{1}中使用这样的方法。您需要单独绑定它们。此外,您应该注意不推荐live方法。 JQuery documentation给出了哪些方法更适合使用的说明。