Changing div styles using a javascript timer with

2019-07-27 10:57发布

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条回答
ゆ 、 Hurt°
2楼-- · 2019-07-27 11:14

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;
}
查看更多
登录 后发表回答