jQuery DIV扩展了鼠标悬停时的契约

时间:2013-02-23 02:21:08

标签: javascript jquery

我有一套四个DIV,每个都是一个段落的标题。我希望每个DIV在悬停时展开以显示一个短段,然后在mouseout上收缩。 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');
        });
     });

也许有更好的方法来实现这个目标?

1 个答案:

答案 0 :(得分:1)

每次悬停时,您都会绑定mouseleave事件。 .hover也有两个参数:一个用于mouseenter的函数和一个用于mouseleave的函数,所以你可以这样写:

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

我还添加了.stop,以便在您快速移入和移出元素时触发另一个动画时暂停当前动画。

相关问题