如何使用HTML倒数计时器? [英] How can I do a countdown timer with html?

查看:57
本文介绍了如何使用HTML倒数计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在帮助我的信息技术老师为某些任务创建复活节彩蛋,并且我想使用html创建一个倒数计时器.解释:每次您进入网站时,倒数计时器都会启动.例子:我有一个带有30分钟倒数计时器的html代码,如果我进入网站,倒数计时器将开始计时,但是如果刷新网站,它将重置.希望您能理解,谢谢!

I'm helping my I.T teacher to create easter eggs for some tasks, and I would like to create a countdown timer with html. Explanation: Everytime you enter into a website, the countdown timer starts. Example: I have a html code with a countdown timer at 30 min, if I go into the website, the countdown timer starts going down, but if I refresh the website, it reset. I hope you will understand, thanks!

推荐答案

如果只想使用javascript,而不使用任何服务器端语言,则可以将剩余的时间存储在localStorage变量中,因为退出网站后,/浏览器,它将保持不变;

If you want to use only javascript, without any server-side language you could store the time that is left in the localStorage variable, because after you exit the website/browser it will stay the same;

示例:

function countdown() {
    time = parseInt(localStorage.time); //All variables in localstorage are strings
    //Resets timer if cannot parse the localStorage.time variable or if the time is greater than 30 mins
    if(isNaN(time) || time > (30*60)) {
        alert("An error occured: time left variable is corrupted, resetting timer");
        localStorage.time = 30*60; //30 mins in seconds
        countdown();
        return null;    
    }
    //Decrementing time and recalling the function in 1 second
    time--;
    localStorage.time = time;
    setTimeout('countdown()', 1000);
}

您可以添加一个将秒数转换为秒的函数:分钟:秒并对其进行编辑,以便每次调用它自己时都会更改元素,或者在时间到0时执行某项操作(不要忘记一次调用它,除非计时器不运行).祝你好运!

You can add a function that turn seconds into: Minutes:Seconds and edit the function so it will change an element everytime it calls it self, or do something when the time reaches 0(don't forget to call it once, unless the timer won't run). Good luck!

我为您制造了一支笔: http://codepen.io/DaCurse0/pen/kkxVYP

I made a pen for you: http://codepen.io/DaCurse0/pen/kkxVYP

它应该具有您需要的一切.

It should have everything you need.

P.S:您可能应该在检查计时器是否损坏时删除警报,因为它会在未设置计时器时显示.

P.S: you should probably remove the alert when checking if timer is corrupted because it will show when the timer wasn't set.

这篇关于如何使用HTML倒数计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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