jQueryDIV在悬停时展开,在鼠标悬停时收缩



我有一组四个div,每个div都是一个段落的标题。我希望每个DIV在悬停时展开以显示一小段,然后在鼠标悬停时收缩回来。jQuery运行正常。唯一的问题是,如果我快速地在四个DIV上来回追踪光标几次,它似乎会破坏函数。

它只是随机地扩展和收缩各种DIV,没有任何明显的模式。

    $('#iam_writer').hover(function(){
        $(this).animate({'height' : '120px'}, 'slow');
        $(this).on('mouseleave',function(){
            $(this).animate({'height' : '25px'}, 'fast');
        });                                     
    });     
    $('#iam_social').hover(function(){
        $(this).animate({'height' : '135px'}, 'slow');
        $(this).on('mouseleave',function(){
            $(this).animate({'height' : '25px'}, 'fast');
        });
    });
    $('#iam_creative').hover(function(){
        $(this).animate({'height' : '135px'}, 'slow');
        $(this).on('mouseleave',function(){
            $(this).animate({'height' : '25px'}, 'fast');
        });
    });
    $('#iam_strategic').hover(function(){
        $(this).animate({'height' : '140px'}, 'slow');
        $(this).on('mouseleave',function(){
            $(this).animate({'height' : '30px'}, 'fast');
        });
     });

也许有更好的方法来实现这一点?

每次悬停在mouseleave事件上时,都会绑定该事件。.hover还接受两个参数:一个用于mouseenter的函数,另一个用于mouseleave的函数,所以可以这样写:

$('#iam_writer').hover(function(){
    $(this).stop().animate({'height' : '120px'}, 'slow');
}, function () { 
    $(this).stop().animate({'height' : '25px'}, 'fast');
}); 

我还添加了.stop,这样,如果触发另一个动画,任何当前动画都会暂停,当您快速移入和移出元素时,就会发生这种情况。

最新更新