在另一个div onClick和onMouseLeave内动画div

时间:2013-12-24 10:33:24

标签: javascript jquery jquery-animate mouseleave

这就是我想要实现的目标:我有一个div(在下面的图像中标记为黑色),其中包含另外2个div(标记为红色和蓝色) - 一个具有单个图像并显示,另一个具有3张图片,目前已隐藏。

enter image description here

当用户点击单个图像时,其父div会生成一个上滑动画并隐藏,第二个div显示。

enter image description here

当用户离开父div区域时 - 它会向下滑动动画并返回初始状态(图像1)。

我编写了这段代码来制作幻灯片:

$(".img_btn_info").click(function(){
    $(this).parent().animate({'margin-top': '-30px'}, 500);
});

它运作得很好。但是现在我尝试编写第二部分的代码,当鼠标离开时,它没有按照我的预期工作 - 它在父div而不是第一部分上动画。

$(".img_btn_info").click(function(){
    $(this).parent().animate({'margin-top': '-30px'}, 500, function(){
        $(this).parent().parent().mouseleave(function(){
            $(this).animate({'margin-top': '30px'}, 500);
        });
    });
});

那么我怎样才能正常工作呢?

更新

这是代码的jsfiddle

2 个答案:

答案 0 :(得分:1)

尝试改变这个:

$(".img_btn_info").click(function(){
    $(this).parent().animate({'margin-top': '-30px'}, 500, function(){
        $(this).parent().parent().mouseleave(function(){
            $(this).animate({'margin-top': '30px'}, 500);
        });
    });
});

到此:

    $(".img_btn_info").click(function(){
        var $here = $(this).parent();
        $here.animate({'margin-top': '-30px'}, 500, function(){
            $(this).parent().mouseleave(function(){
                $here.animate({'margin-top': '0'}, 500);
            });
         });
     });

DEMO

答案 1 :(得分:0)

我会直接调用所有DOM元素,而不是使用.parent()。parent()。等

E.g。类似的东西:

$(".img_btn_info").click(function(){
    $('#second-box').animate({'margin-top': '-30px'}, 500, function(){
        $('#container').mouseleave(function(){
        $('#second-box').animate({'margin-top': '30px'}, 500);
        });
    });
});
相关问题