【问题标题】:Can not stop the slider无法停止滑块
【发布时间】:2015-03-31 21:54:23
【问题描述】:

尝试制作最简单的画廊。有一个按钮可以转动图像<button class = "play-pause">Play</ button>。点击它会启动setInterval,但再次按下时需要让它停止。如何做到这一点?

这里是沙盒的链接:http://jsfiddle.net/eL31q3eq/

我的尝试:

document.querySelector('.play-pause').addEventListener('click', function() {
    if(timer == null) clearInterval(timer);

    this.innerHTML = "Pause";

    timer = setInterval(function() {
        i = (i < images.length - 1) ? ++i : 0;
        img.src = images[i];
    }, 1000);

    timer = null;
});

【问题讨论】:

标签: javascript


【解决方案1】:

您正在丢弃停止幻灯片放映所需的变量 - 此处的解决方案。

http://jsfiddle.net/obh5tanL/

也不要初始化你的计时器变量。

document.querySelector('.play-pause').addEventListener('click', function() {
    if (timer) {
        clearInterval(timer);
        this.innerHTML = "Play";
    }
    else {
        this.innerHTML = "Pause";

        timer = setInterval(function() {
            i = (i < images.length - 1) ? ++i : 0;
            img.src = images[i];
        }, 1000);
    }

});

【讨论】:

    【解决方案2】:

    问题在于clearInterval 将区间对象作为参数,并将其清除。您将 timer 设置为 null,因此您要求它清除 null,这意味着它不会做任何事情。

    WindowTimer.clearInterval - MDN

    您需要使用其他变量来检查播放/暂停按钮的状态。

    document.querySelector('.play-pause').addEventListener('click', function() {
    
    if(playing === true) {
        this.innerHTML = 'Play';
        clearInterval(timer);
        playing = false;
        return;
    }
    
    this.innerHTML = "Pause";
    
    timer = setInterval(function() {
        i = (i < images.length - 1) ? ++i : 0;
        img.src = images[i];
    }, 1000);
    
    playing = true;
    

    });

    http://jsfiddle.net/eL31q3eq/2/

    【讨论】:

    • 有些事情我不太明白你的决定。 jsfiddle.net/obh5tanL/1
    • 嘿,Aleksandr,似乎对我有用。无论哪种方式,我都更新了我的代码以更准确地反映您的风格并添加了一个有效的 jsFiddle
    • 在你的帖子中老小提琴,我的帖子中的那个。
    猜你喜欢
    • 1970-01-01
    • 2016-05-13
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多