简体   繁体   English

使用jQuery单击按钮来停止动画

[英]Stop an animation with a button click using jquery

I'm trying to pause the animation that I have running and I have no idea what I'm doing. 我试图暂停正在运行的动画,但我不知道自己在做什么。

I also tried "function stop() { clearInterval(changer) }". 我还尝试了“函数stop(){clearInterval(changer)}”。

HTML and JQUERY below 下面的HTML和JQUERY

```
    <div id="change"></div>
    <button id="stop">Stop</button>```

```
    $(function() {
    changer();
    });
    function changer() {
    var words = ["a", "b", "c", "d", "e", "f", "g", "h"];
    var idx = Math.floor(words.length * Math.random());
    $('#change').text(words[idx]);
    var time = Math.floor (100 * Math.random() + 75);
    setTimeout(changer, time);
    }

    function stop() {
        $("#change").stop(true);
        }```

JSFIDDLE: https://jsfiddle.net/magoo/a6kt8qmf/1/ JSFIDDLE: https ://jsfiddle.net/magoo/a6kt8qmf/1/

Please help an idiot. 请帮助白痴。 Thank you in advance. 先感谢您。

Add a variable that can act as an boolen 'stopIT', in this case setTimeout can't be called, when stop function han been called. 添加一个可以充当布尔值“ stopIT”的变量,在这种情况下,当调用stop函数时,无法调用setTimeout。

var stopIT = false;
function changer() {
   var words = ["a", "b", "c", "d", "e", "f", "g", "h"];
   var idx = Math.floor(words.length * Math.random());
   $('#change').text(words[idx]);
   var time = Math.floor (100 * Math.random() + 75);
   stopIT === false && setTimeout(changer, time);
}

function stop() {
    stopIT = true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM