Changing div styles using a javascript timer with different intervals

五迷三道 提交于 2019-12-13 00:10:13

问题


Currently I have the following code creating my timer:

<script type="text/javascript">
var interval;
var minutes = 8;
var seconds = 10;

function countdown(element) {
    interval = setInterval(function() {
        var el = document.getElementById(element);
        if(seconds == 0) {
            if(minutes == 0) {
                alert(el.innerHTML = "countdown's over!");                    
                clearInterval(interval);
                return;
            } else {
                minutes--;
                seconds = 60;
            }
        }
        if(minutes > 0) {
            var minute_text = minutes + (minutes > 1 ? ' minutes' : ' minute');
        } else {
            var minute_text = '';
        }
        var second_text = seconds > 1 ? 'seconds' : 'second';
        el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + ' remaining';
        seconds--;
    }, 1000);
}
</script> 

And I use the following buttons to trigger it:

<input type="button" onclick="countdown('countdown');" value="Start" />
<input type="button" onclick="clearInterval(interval);" value="Pause" />

How can I track the timer and change page styles as time goes by?

For example, when I click start I want to highlight one div, after 5 seconds I want to highlight another div and unhighlight the first, 20 seconds after that I want to change the highlight again, 10 seconds after that I change the highlight again, and so on.

The intervals should be able to be different times, but most cases will follow the pattern above (0, 5, 5, 20, 10, 20, 10, 20, 10...) so that's a good starting place. The total length of the timer is always 8 minutes, so the intervals can be hard coded and I could use PHP to select the correct code (although inefficient, probably easiest).

Anyone have any ideas?


回答1:


Put in a switch statement on the elapsed time.

For each specified interval, set the div in question, and unset the others.

//at the beginning of the script
var origtime = minutes*60+seconds;

//...snip to countdown function

var timeleft = minutes*60+seconds;
switch(origtime - timeleft)
{
case 0: highlightfirstdiv(); break;
case 5: highlightseconddiv(); break;
case 10: highlightthirddiv(); break;
...
case x: highlightfinaldiv(); break;
}


来源:https://stackoverflow.com/questions/10417571/changing-div-styles-using-a-javascript-timer-with-different-intervals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!