【问题标题】:pause jquery animation on hover, stop on click悬停时暂停jquery动画,点击停止
【发布时间】:2013-04-11 07:01:55
【问题描述】:

我正在尝试制作一个网页,其中一组 DIV 从上到下循环(参见小提琴)。然后,每当您将鼠标悬停在 div 的某个部分(在本例中为 STOP 链接)时,动画就会停止,然后在鼠标移出时再次播放。我现在缺少的是一种在单击 STOP 链接时停止动画的方法。我在链接上添加了停止功能,但它不起作用。我制作的悬停功能可能存在冲突或某种原因。

在此先感谢您的帮助,并对这个愚蠢的问题表示歉意。

小提琴链接:http://jsfiddle.net/Psp9R/

jquery:

$(document).ready(function() {

$(".row").last().addClass("last");
$(".mholder").each(function() {
    var i = 0;
    $(this).find(".row").each(function() {
        var $this = $(this);
        $this.css("bottom", i);
        i += $this.height();
    });
});

// PLAY AND STOP
$('#start').click(function() {
    $("#overlay").hide();
    var countScrolls = $('.mholder .row').length;

    for (var i=0; i < countScrolls; i++) {
       doScroll($('.mholder .row:nth-child(' + i + ')'));
    }
});

$('.stop').click(function() {
    var countScrolls = $('.mholder .row').length;
    $("#overlay").show();
     for (var i=0; i < countScrolls; i++) {
       $('.mholder .row:nth-child(' + i + ')').stop();
    }
});

//PAUSE ON HOVER

$(".stop").hover(function () { 
    var countScrolls = $('.mholder .row').length;
     for (var i=0; i < countScrolls; i++) {
       $('.mholder .row:nth-child(' + i + ')').stop();
    }
}, function () {
    var countScrolls = $('.mholder .row').length;

    for (var i=0; i < countScrolls; i++) {
       doScroll($('.mholder .row:nth-child(' + i + ')'));
    }
});

});

function doScroll($ele) {
var bottom = parseInt($ele.css("bottom"));
    if (bottom < -60) { //bit arbitrary!
    var $lastEle = $ele.closest('.mholder').find(".last");
    $lastEle.removeClass("last");
    $ele.addClass("last");
    var bottom = (parseInt($lastEle.css("bottom")) + $lastEle.height());
    $ele.css("bottom", bottom);
    }
    $ele.animate({
        bottom: (parseInt(bottom) - 80)
    }, 2200, 'linear', function() {
        doScroll($(this))
    });
}

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您知道吗,当您单击停止时,它确实停止了,但是当您将鼠标移出停止按钮时,浏览器会知道您触发了 mouseout 事件并恢复其慢跑。因此,您必须告诉浏览器您单击停止按钮并忽略 mouseout 事件。我通过添加标志iStop 以命令浏览器停止来更改您的代码。您可以通过以下方式查看:jsFiddle

    【讨论】:

    • 是的,功能好像有冲突。我问过一个人,你们的答案都是一样的。非常感谢!
    【解决方案2】:

    实现一个间隔,当单击停止链接时清除该间隔,然后在鼠标移出时重新开始。

    setInterval - https://developer.mozilla.org/en/docs/DOM/window.setInterval

    clearInterval - https://developer.mozilla.org/en-US/docs/DOM/window.clearInterval

    【讨论】: