【问题标题】:Javascript: Putting a looping jQuery animation inside a js functionJavascript:在 js 函数中放置一个循环的 jQuery 动画
【发布时间】:2016-03-10 07:36:05
【问题描述】:

我想在 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();
});

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

【问题讨论】:

  • 定义“打破播放功能”。另外,你为什么不能把animateBox() 放在你的play 函数中?除非我误会了。
  • 嗨,马特:我的意思是播放功能停止工作,当我向其中添加 animateBox 功能时——我以几种不同的方式做错了;我不知道如何正确地做到这一点。

标签: javascript jquery jquery-animate


【解决方案1】:

这应该可行。我没有用音频对象尝试过,但动画循环应该是正确的。这是一个没有音频对象的 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 );

【讨论】:

  • 谢谢,Bjorn -- 但它在我的页面上对我不起作用。音频不播放,动画不开始。看这里:carolineingles.com你知道问题可能是什么吗?
  • 是的,您将两次触发play(),一次在html标签onClick上,另一次在我的代码中使用$( "#playButton" ).click( play )。删除其中之一。问题,您熟悉浏览器中的开发者工具吗?
  • 就是这样!有用!我不知道开发人员工具,但我会检查它们。再次感谢您帮助我!
  • 欢迎您。你一定要检查他们。你真的不想没有他们。 Yuo 可以检查您的脚本是否正确加载,脚本是否导致错误,甚至可以检查是否调用了特定函数(以及使用哪些参数)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-10
  • 2014-04-19
  • 2016-02-04
  • 1970-01-01
  • 2013-03-04
  • 2019-07-06
  • 1970-01-01
相关资源
最近更新 更多