发生mousemove事件时暂停动画

时间:2013-05-21 12:53:39

标签: javascript jquery

我有以下代码:

$(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';

    },

问题是当mousemove事件发生时我应该清除动画队列,但是我有转换动画需要先完成。这两种效果都应用于同一个元素,所以如果我简单地写下面的内容:

$img.clearQueue().stop();

...不显示过渡动画。

您可以在以下小提琴中看到实时示例:http://jsfiddle.net/SL8t7/

2 个答案:

答案 0 :(得分:1)

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

这样,只有在转换完成后才会触发mousemove。

这是一个jsfiddle,其中包含我提出的更改

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;
                }

答案 1 :(得分:1)

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

$(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,但我认为你明白了。

相关问题