jQuery animate()快速悬停时序列乱序

时间:2017-10-11 13:20:00

标签: javascript jquery html css animation

我用jQuery创建了一个动画,它依次(反向)在文本行中滑动。它非常简单,在悬停一次时效果很好。然而,当快速移动鼠标时,线条将以看似随机的顺序生成动画。

请参阅下面的GIF进行演示。第一个悬停是动画的外观。在悬停之后,我将鼠标移入和移出以演示文本行随机动画的问题。

enter image description here

请参阅下面的代码示例:

HTML

<div class="image-block">
    <p>Text Line 1</p>
    <p>Text Line 2</p>
    <p>Text Line 3</p>
    <p>Text Line 4</p>
    <p>Text Line 5</p>
</div>

CSS

/* Hide text lines to begin with */
.image-block {
    position: relative;
    overflow: hidden;
    background-image: url('background-image.png');
}
.image-block p {
    position: absolute;
    left: -120%
}

的jQuery

jQuery(document).ready(function() {
    // Animate text lines on hover with CSS 'left'.
    jQuery('.image-block').hover(function() {
        jQuery.fn.reverse = [].reverse;
        time = 0;
        speed = 300;
        jQuery(this).find('p').reverse().each(function() {
            jQuery(this).stop(true).delay(time).animate({
                left: '0'
            }, speed,
            function() {
                jQuery(this).stop(true).delay(time).animate({
                    left: '0'
                }, speed);
            })
            time = time + 125;
            speed = speed - 25;
        });
    }, function() {
        // Animate text lines on hover release with CSS 'left'.
        jQuery(this).find('p').reverse().each(function() {
            jQuery(this).stop(true).animate({
                left: '-120%'
            }, 150)
        });
    });
});

当快速移动鼠标时,前两行如何首先制作动画?悬停发布后,我是否需要以某种方式重置动画?我在动画中添加了stop(true),但这并没有解决问题。

提前谢谢。

1 个答案:

答案 0 :(得分:0)

这让我也摸不着头脑。正如我之前已经解决过这个问题,但为了解释起见,必须详细说明。

问题在于您使用动画制作的GetMethod()方法。向动画添加延迟时,无法清除它。因此,当您快速hoverIn / hoverOut时,以前的悬停事件中的处理程序不会被清除,并且某些.delay()标记会不按顺序进行动画处理。有关p的详细说明,请在StackOverflow或更好jQuery delay

检查所选答案

关于问题的解决方案。您可以使用.delay()替代setTimeout。我已使用此jsfiddle作为使用delay解决问题的解决方法。

您可以使用setTimeout

这样做
setTimeout

在为悬停(MouseIn)添加动画时,您需要将jQuery(document).ready(function() { // Animate text lines on hover with CSS 'left'. // To store setTimeout response var animations = new Array(5); jQuery('.image-block').hover(function() { jQuery.fn.reverse = [].reverse; time = 0; speed = 300; jQuery(this).find('p').reverse().each(function(index, item) { // Clear previous handlers clearTimeout(animations[index]); // Set new handlers and add to `animations` animations[index] = setTimeout(function(){ jQuery(item).stop(true).animate({ left: '0' }, speed); }, time); time = time + 125; speed = speed - 25; }); }, function() { // Animate text lines on hover release with CSS 'left'. jQuery(this).find('p').each(function(index, item) { // Clear previous handlers clearTimeout(animations[index]); jQuery(item).stop(true).animate({ left: '-120%' }, 150); }); }); }); 返回值保存到变量,以便您可以在MouseOut时清除这些值。如果您需要更多关于小提琴的解释,请回复。

更新: setTimeout实际上并不需要,所以删除它并更新小提琴代码。