CountDown计时器:暂停按钮不会暂停或更改回播放按钮

时间:2015-12-26 01:18:56

标签: javascript html html5 countdown

我在尝试暂停倒数计时器方面遇到了麻烦。我点击播放按钮后,我试图这样做,按钮变成了一个暂停按钮。但出于某种原因,它不会停顿。

我试图更改ID" pButton" to" pauseButton",这是有效的,但似乎我的暂停onclick功能不会改回pButton,任何帮助?(clearinterval(timecounter),timercounter是一个全局可变的,所以它可以访问如果您需要查看:http://codepen.io/freefora11/pen/eJdVjZ

,此处还有代码笔上的完整代码
//when play button is pressed
    if(document.getElementById("pButton")){
        document.getElementById("pButton").onclick=function(){

            //change the id of the button
            if(document.getElementById("pButton")){
                document.getElementById("pButton").id = "pauseButton";
            }

            //variables
            strMin = document.getElementById("test").innerHTML;
            var res = strMin.split(":",2);
            min = parseInt(res[0]);
            min= min * 60;
            var sec = parseInt(res[1]);
            timeInSeconds = min + sec;



            //set interval to start keeping track each second that has passed
            timeCounter = setInterval(function() {
              timeInSeconds--;

              // If we hit 0 seconds clear the timer
              if (timeInSeconds <= 0) {
                clearInterval(timeCounter);
              }

              // Display the current time
              displayTime();
            }, 1000);
        }
    }

    //when the pause button is clicked
    if(document.getElementById("pauseButton")){
        document.getElementById("pauseButton").onclick=function(){

            //stop the interval
            clearInterval(timeCounter);

            //change the id of the play button from pauseButton to pButton again
            if(document.getElementById("pauseButton")){
                document.getElementById("pauseButton").id ="pButton";
            }

        }
    }

1 个答案:

答案 0 :(得分:1)

更改ID仍会在DOM中留下处理程序的剩余部分。因此,当您运行您的codepen并单击“开始/暂停”按钮时,您会注意到它正在向计时器添加另一个倒计时。这就是每次单击按钮时倒计时速度加快的原因。

您应该在按钮的一个处理程序中处理click事件的状态。如果状态暂停,则处理暂停逻辑。如果它正在运行,那么处理你正在运行的逻辑。但是从一个事件处理程序完成所有操作。在这种情况下使用id或class很好,但不要在运行中交换它。如果有的话,使用点击处理程序的Id,然后在dom中的元素上交换类(或应用数据属性)将更好地表达时钟的当前状态/模式。

尽管如此,处理你的javascript中的逻辑。如果您选择这样做,请使用dom状态来应用样式(例如,在CSS中选择)。

相关问题