Javascript:将循环jQuery动画放在js函数中

Javascript: Putting a looping jQuery animation inside a js function

本文关键字:js 函数 动画 循环 jQuery Javascript      更新时间:2023-09-26

我想在js函数中嵌套一个循环jQuery动画函数,但我不知道该怎么做。

我有一个音频文件,当单击div 时播放(如果再次单击div 会暂停),同时div 文本从播放符号变为暂停符号。我想在播放音乐时对另一个div 进行动画处理,并在音乐暂停时停止动画。

这是我的音频函数代码:

function play() {
    var audio = document.getElementById('whatchaDoin');
    if (audio.paused) {
        audio.play();
        document.getElementById('playButton').innerHTML = ''u2016';
    } else {
        audio.pause();
        document.getElementById('playButton').innerHTML = ''u25BA';
    }
}

这是我的动画:

$(document).ready(function() {
    function animateBox() {
        $('#greenBox').animate({
            'margin-top': '20px',
            'height': '150px',
            'width': '150px'
        }, 195).animate({
            'margin-top': '30px',
            'height': '140px',
            'width': '140px'
        }, 390, animateBox);
    }
    animateBox();
});

我似乎找不到一种方法在不破坏播放功能的情况下将它们放在一起。感谢您给我的任何帮助!

这应该有效。我还没有尝试过使用音频对象,但动画循环应该是正确的。这是一个没有音频对象的jsFiddle:https://jsfiddle.net/5fwdcq37/1/

下面的代码应该是带有音频的,重要的是要知道,当您在 jquery 中停止动画并将"jumpToEnd"标志设置为true它将触发完整的函数。在之前的示例中,将再次启动动画循环,因此您将永远无法停止它。因此,您需要添加一个额外的变量loop来检查它是否应该循环:

function play() {
    var audio = document.getElementById('whatchaDoin');
    if (audio.paused) {
        audio.play();
        document.getElementById('playButton').innerHTML = ''u2016';
        startAnimation();
    } else {
        audio.pause();
        document.getElementById('playButton').innerHTML = ''u25BA';
        stopAnimation();
    }
}
var loop = false;
function startAnimation(){
   loop = true;
   $('#greenBox').animate({
            'margin-top': '20px',
            'height': '150px',
            'width': '150px'
        }, 195).animate({
            'margin-top': '30px',
            'height': '140px',
            'width': '140px'
        }, 390, function(){ if(loop){ startAnimation(); } });
}
function stopAnimation(){
  loop = false;
  $('#greenBox').stop( true, true );
}
$( "#playButton" ).click( play );