每次刷新页面时,我的倒数计时器都会重置。 无论页面刷新多少次,我都需要将此倒数计时器重置为零时重置。
我不知道如何使倒数计时器那样工作,您能帮我吗?
我需要这样的内容:https://intellywp.com/evergreen-countdown-timer
这是我的代码:
function contador() {
var hr = "23";
var mm = "59";
var ss = "59";
var interval = setInterval(function(){
if(hr == 0 && mm == 0 && ss == 0)clearInterval(interval);
ss--;
if(ss == 0)
{
ss = 59;
mm--;
if(mm == 0)
{
mm = 59;
hr--;
}
}
if(hr.toString().length < 2) hr = "0"+hr;
if(mm.toString().length < 2) mm = "0"+mm;
if(ss.toString().length < 2) ss = "0"+ss;
$("#contador").html("<span class='hora'>"+hr+"</span> : <span class='minuto'>"+mm+"</span> : <span class='segundo'>"+ss+'</span>');
},1000)
}
window.onload = contador;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="contador" class="py-4"></div>
答案 0 :(得分:0)
在每个间隔上,只需将一些内容设置到本地存储中即可
function contador() {
var hr = localStorage.getItem('hr');
var mm = localStorage.getItem('mm');
var ss = localStorage.getItem('ss');
if (!hr || !mm || !ss) {
hr = "23";
mm = "59";
ss = "59";
localStorage.setItem('hr', hr);
localStorage.setItem('mm', mm);
localStorage.setItem('ss', ss);
}
var interval = setInterval(function(){
if(hr == 0 && mm == 0 && ss == 0)clearInterval(interval);
ss--;
if(ss == 0)
{
ss = 59;
mm--;
if(mm == 0)
{
mm = 59;
hr--;
}
}
if(hr.toString().length < 2) hr = "0"+hr;
if(mm.toString().length < 2) mm = "0"+mm;
if(ss.toString().length < 2) ss = "0"+ss;
$("#contador").html("<span class='hora'>"+hr+"</span> : <span class='minuto'>"+mm+"</span> : <span class='segundo'>"+ss+'</span>');
localStorage.setItem('hr', hr);
localStorage.setItem('mm', mm);
localStorage.setItem('ss', ss);
},1000)
}
window.onload = contador;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="contador" class="py-4"></div>
注意:如果本地存储中缺少 任何 个变量,计时器将重置为23:59:59。
答案 1 :(得分:0)
我已经对其进行了一些修改以满足我的需求,但这是最好的解决方案。
function contador() {
var hr = $('input[name="hr"]').val();
var mm = $('input[name="mm"]').val();
var ss = $('input[name="ss"]').val();
var interval = setInterval(function(){
if(hr == 0 && mm == 0 && ss == 0)clearInterval(interval);
ss--;
if(ss == 0) {
ss = 59;
mm--;
if(mm == 0) {
mm = 59;
hr--;
}
}
if(hr.toString().length < 2) hr = "0"+hr;
if(mm.toString().length < 2) mm = "0"+mm;
if(ss.toString().length < 2) ss = "0"+ss;
$("#contador").html("<span class='hora'>"+hr+"</span>h <span class='minuto'>"+mm+"</span>m <span class='segundo'>"+ss+'</span>s');
},1000)
}
window.onload = contador;