悬停暂停滚动

3

我正在为一个滚动的div添加动画效果,已经成功实现了点击或鼠标进入时触发滚动并停止。现在我想要在鼠标悬停在div上时暂停滚动,而不是停止。由于我完全不懂jquery,所以真的不知道什么方法可行。以下是我的代码,目前它能够正常工作。

$(document).ready(function() {
    var sL = 4000;
    $('.scrolls').animate({
        scrollLeft : sL
    },100000, 'linear');

    $(".scrolls").on("click",function(){
        $(this).stop(true,false);
    });

})

任何帮助都非常感激!!
谢谢! http://jsfiddle.net/BMb65/9/

1
请查看 jQuery 文档中的 queuedequeue - Sterling Archer
谢谢!我已经研究过了,但是还没有弄清楚如何将所有东西组合在一起。看起来应该很容易,但当然...我能否简单地用.dequeue替换.stop,还是必须完全重新配置代码?这里有一个jsfiddle http://jsfiddle.net/BMb65/9/ - user3158649
我为你的代码编写了一个修改后的版本,可以按照你的要求工作。请查看下面的答案并进行审核。 - Mohammed R. El-Khoudary
3个回答

1
这应该可以工作:

$(document).ready(function() {
    var $div = $('.scrolls');
    var sL = 4000;
    var startTime = new Date().valueOf();
    var timePassed;
    var stopped = false;
    //animate:
    $div.animate({
        scrollLeft : sL
    },100000, 'linear');

    //on click, stop animation:
    $div.on("click",function(){
        $div.stop(true,false);
        stopped = true;
    });

    //on mouseover -> stop animation (pause)
    //on mouseout -> resume animation (actually a new animation
    $div.hover(function() { //mouseenter
        $div.stop(true, false);
        timePassed = (new Date()).valueOf() - startTime;
    }, function() { //mouseleave
        if (!stopped) { //resume only if it was stopped on mouse enter, not on click
            $div.animate({
                scrollLeft : sL
            }, 100000 - timePassed, 'linear');
        }
    });
});

使用此代码,当您将鼠标悬停在div上时,动画会停止。我们记录自开始以来经过的时间,因此我们可以创建一个新的动画,通过将其持续时间设置为原始持续时间减去已经过去的时间,来模拟旧动画的恢复。希望这能帮到您。

很高兴能帮到您。请将答案标记为正确。 - Oscar Paz

1

为什么不使用mouseenter和mouseleave事件..

请查看这个fiddle: 修改后的代码

基本上你将会做类似于这样的事情:

 $(".scrolls").on("mouseenter",function(){
    $(this).stop(true,false);
});

$(".scrolls").on("mouseleave",function(){
    $(this).animate({
    scrollLeft : sL
    },100000, 'linear');
});

1
请查看这个fiddle http://jsfiddle.net/93Ta8/ 我所做的就是利用
$(".scrolls").on("mouseenter"

并且

$(".scrolls").on("mouseleave"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接