使用具有不同间隔的 javascript 计时器更改 div 样式 [英] Changing div styles using a javascript timer with different intervals

查看:34
本文介绍了使用具有不同间隔的 javascript 计时器更改 div 样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有以下代码创建我的计时器:

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?

例如,当我单击开始时,我想突出显示一个 div,5 秒后我想突出显示另一个 div 并取消突出显示第一个,20 秒后我想再次更改突出显示,10 秒后我更改再次突出显示,依此类推.

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.

间隔应该可以是不同的时间,但大多数情况下会遵循上述模式(0、5、5、20、10、20、10、20、10...),所以这是一个很好的起点.计时器的总长度始终为 8 分钟,因此可以对间隔进行硬编码,我可以使用 PHP 来选择正确的代码(虽然效率低下,但可能最简单).

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).

有人有什么想法吗?

推荐答案

在经过的时间放入 switch 语句.

Put in a switch statement on the elapsed time.

对于每个指定的间隔,设置有问题的 div,并取消设置其他的.

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;
}

这篇关于使用具有不同间隔的 javascript 计时器更改 div 样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆