我正在建立一个柜台,并有一些问题.我有一个计数器字段,其中增量和减量发生(默认情况下,它是5分钟).按下"开始"按钮时,最终计数器的数字应设置为输出字段中的计时器.这是我的解决方案:
;(function(){ var output = document.querySelector('#output'), btn = document.querySelector('button'), min = 5, sec = min * 60, timer; setCount(min); function setCount(n){ var c = document.querySelector('#counter'), increment = c.children[1].children[0], decrement = c.children[1].children[2], num = c.children[1].children[1]; increment.onclick = function(){ if(n >= 1) {num.textContent = ++n;} }; decrement.onclick = function(){ if(n > 1) {num.textContent = --n;} }; num.textContent = n; } function setTimer(){ var currentMin = Math.round((sec - 30) / 60), currentSec = sec % 60; if(currentMin >= 0 ) {currentMin = '0' + currentMin;} if(currentSec <= 9 ) {currentSec = '0' + currentSec;} if(sec !== 0){sec--;} timer = setTimeout(setTimer,10); // 10 is for the speedy output.textContent = currentMin + ':' + currentSec; } btn.addEventListener('click', setTimer, false); })();
这是链接:JS Bin