倒计时计时器:暂停按钮获胜't暂停或改回播放按钮
CountDown Timer: pause button won't pause or change back into play button
我在尝试暂停倒计时计时器时遇到问题。我正在努力做到这一点,所以在我点击播放按钮后,按钮变成了暂停按钮。但出于某种原因,它不会暂停。
我试图将id"pButton"更改为"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";
}
}
}
更改Id仍然会在DOM中留下剩余的处理程序。因此,当你运行代码笔并单击"开始/暂停"按钮时,你会注意到它正在为计时器添加另一个倒计时。这就是为什么每次点击按钮时倒计时都会加快的原因。
您应该在按钮的一个处理程序中处理单击事件的状态。如果状态已暂停,则处理您的暂停逻辑。如果它正在运行,那么处理您的运行逻辑。但要从一个事件处理程序中完成所有操作。在这种情况下,使用id或class是可以的,但不要随意交换。如果有什么不同的话,使用单击处理程序的Id,然后在dom中交换元素上的类(或应用数据属性)将更好地表达时钟的当前状态/模式。
尽管如此,还是要处理javascript中的逻辑。如果您选择使用dom状态来应用样式(例如在CSS中选择)。
相关文章:
- jQuery:暂停按钮可以暂停所有其他操作
- 具体化:如何只使用HTML和Javascript制作播放/暂停按钮
- 在 jquery 中定位暂停和播放按钮
- 在 html5 中使用暂停和播放按钮
- 暂停按钮代码
- 带有音频标签的多个播放/暂停按钮
- 单击时暂停音频并更改按钮的图像
- 如何使按钮从暂停变为播放
- HTML5 Javascript播放/暂停按钮
- 在按钮上单击暂停HTML视频(正在自动播放)
- <音频>播放/暂停按钮更改
- 可以't使用居中的大播放按钮暂停VideoJS播放器
- 使用HTML5和JavaScript播放/暂停音频按钮
- 使用导航按钮后,幻灯片需要暂停
- 使用 HTML5 和 JavaScript 播放/暂停音频按钮
- 在HTML音频播放器中切换播放/暂停按钮
- 弹性滑块暂停按钮
- 在仅幻灯片 JavaScript 上添加播放/暂停按钮
- 在图像上迭代,然后使用jQuery按下按钮暂停
- 切换HTML按钮暂停和恢复功能