我需要一个24小时倒数计时器,就像链接中的图像一样。我需要在我的wordpress网站上实现计时器。计时器应该在美国东部时间午夜每晚重置。
这是我当前的JS代码,但每次刷新页面时都会重新启动。我能以某种方式将它与EST整合吗?
<script type = "text/javascript">
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval("tick()", 1000);
}
function tick( ) {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
}
else {
clearInterval(ticker);
startTimer(172800); // start again
}
var hours= Math.floor(secs/3600);
secs %= 3600;
var mins = Math.floor(secs/60);
secs %= 60;
var pretty = ( (hours < 10 ) ? "0" : "" ) + hours + ":" + ( (mins < 10) ? "0" : "" ) + mins + ":" + ( (secs < 10) ? "0" : "" ) + secs;
document.getElementById("countdown").innerHTML = pretty;
}
startTimer(86400); // 24 hours in seconds
</script>
<span id="countdown" style="font-weight: bold;"></span>
答案 0 :(得分:1)
当我回到家时,我会再看一下这个问题,但问题是每次加载页面时都会调用startTimer()方法,你需要做的是获取当前系统时间(以EST格式) )并将其转换为秒 这样,当您的页面刷新时,您将拥有当前时间而不是当前定义的常量 - 我希望这是您找到解决方案的基础。
答案 1 :(得分:1)
我得到了答案。正如亚历克斯所说,我需要获得当前的系统时间(EST)。我想出了index.html和server_time.php文件。这是两个文件的代码
INDEX.HTML
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Countdown</title>
<script src="http://code.jquery.com/jquery-2.1.0.js"></script>
<script>
var root_path = "http://localhost/countdown/";
function init(){
$.ajax({
type: "POST",
url: root_path + "server_time.php",
beforeSend: function(aj_msg) {
//$("#countdown").html('');
},
success: function(aj_msg){
$("#countdown").html('');
phpMsg = JSON.parse(aj_msg);
var est = "<span>" + Math.abs(phpMsg['ServerTime'][0].hour) + " :</span> ";
est += Math.abs(phpMsg['ServerTime'][0].minute) + " : " ;
est += Math.abs(phpMsg['ServerTime'][0].second);
$("#countdown").html(est);
}
})
}
setInterval(init, 1000)
</script>
</head>
<body>
<div id="countdown"></div>
</body>
</html>
和server_time.php
<?php
date_default_timezone_set('US/Eastern');
$currenttime = date('G:i:s:u');
list($hrs,$mins,$secs,$msecs) = split(':',$currenttime);
$output = '{"ServerTime": [';
$hrs -= 24;
$mins -= 60;
$secs -= 60;
$output .= '{ "hour":"' . $hrs . '" , "minute":"' . $mins . '", "second":"' . $secs . '"}';
$output .=']}';
echo $output;
?>