鼠标移动事件发生时暂停动画

Pause animation when mousemove event occurs

本文关键字:暂停 动画 移动 事件 鼠标      更新时间:2023-09-26

我有以下代码:

$(source)
.on('mouseenter', start)
.on('mouseleave', stop)
.on('mousemove', zoom.move);

这里我附加了几个鼠标事件监听器。当'mouseenter'事件发生时,执行以下函数:

    automove: function myAutomove() {
        var xPos = rand(0, outerWidth);
        var yPos = rand(0, outerHeight);
        $(img).animate({
            'top': (yPos - offset.top) * -yRatio + 'px',
            'left': (xPos - offset.left) * -xRatio + 'px' 
        }, defaults.speed, myAutomove);
    }

它现在工作得很好,但是当'mousemove'事件发生时,执行以下操作:

    move: function (e) {
        var left = (e.pageX - offset.left),
        top = (e.pageY - offset.top);
        top = Math.max(Math.min(top, outerHeight), 0);
        left = Math.max(Math.min(left, outerWidth), 0);
        img.style.left = (left * -xRatio) + 'px';
        img.style.top = (top * -yRatio) + 'px';
    },

问题是,当鼠标移动事件发生时,我应该清除动画队列,但我有过渡动画需要先完成。这两种效果应用于同一个元素,所以如果我简单地写如下:

$img.clearQueue().stop();

…不显示过渡动画

您可以看到下面的示例:http://jsfiddle.net/SL8t7/

我建议将onmousemove监听器添加到"start"方法中的动画集中。此外,当"stop"方法触发时,我将删除onmousemove侦听器。

这样鼠标移动只在转换完成后才会被触发。

下面是我所建议的修改的概要

http://jsfiddle.net/XrKna/1/

您将看到move事件现在等待转换完成。

我从这里移动了事件绑定…

                $(source)
                .on('mouseenter', start)
                .on('mouseleave', stop);
这里

                function start() {
                    zoom.init();
                    $img.stop().
                    fadeTo($.support.opacity ? settings.duration : 0, 1, function(){$img.on('mousemove', zoom.move)});
                    zoom.automove();
                }
                function stop() {
                    $img.off('mousemove', zoom.move);
                    $img.clearQueue().stop()                    
                    .fadeTo(settings.duration, 0);
                    manual_step = 0;
                }

您可以创建自定义队列。例如:

$(img).animate({
  // properties
},
{
  duration: defaults.speed,
  complete: myAutomove,
  queue: 'autoMove' // here we attached this animation to a custom queue named 'autoMove'
}.dequeue('autoMove'); // for custom queues we have to start them manually

如果你想在自定义队列中停止动画,只需调用:

$(img).stop('autoMove', true); // the 'true' ensures the custom queue is cleared as well as stopped

我没有真正了解你想要停止的动画和你允许继续的动画所以我没有更新你的jsFiddle,但我认为你明白了