我有以下JavaScript倒计时代码:
function getTimeRemaining(deadline) {
var t = Date.parse(deadline) - Date.parse(new Date),
s = Math.floor(t / 1e3 % 60),
m = Math.floor(t / 1e3 / 60 % 60),
h = Math.floor(t / 36e5 % 24),
d = Math.floor(t / 864e5);
return {
total: t,
seconds: s
minutes: m,
hours: h,
days: d
}
}
function initializeClock(clockdiv, deadline) {
var cla = document.getElementById(clockdiv),
days = cla.querySelector(".days"),
hours = cla.querySelector(".hours"),
minutes = cla.querySelector(".minutes"),
seconds = cla.querySelector(".seconds");
function abc() {
var time = getTimeRemaining(deadline);
days.innerHTML = ("0" + time.days).slice(-2),
hours.innerHTML = ("0" + time.hours).slice(-2),
minutes.innerHTML = ("0" + time.minutes).slice(-2),
seconds.innerHTML = ("0" + time.seconds).slice(-2),
time.total <= 0 && clearInterval(s)
}
abc();
var s = setInterval(abc, 1e3)
}
我如何做到这一点,以便在倒数到零时重定向?任何帮助都非常感谢!谢谢!
答案 0 :(得分:2)
您可以使用以下代码段在特定时间段后处理重定向。
使用日历截止日期的建议是使用给定截止日期的毫秒值,然后将其与当前时间相减并设置超时值。
信用额应转到https://gist.github.com/Joel-James/62d98e8cb3a1b6b05102
<!-- Modify this according to your requirement -->
<h3>
Redirecting to Google.com after <span id="countdown">10</span> seconds
</h3>
<!-- JavaScript part -->
<script type="text/javascript">
// Total seconds to wait
var seconds = 10;
function countdown() {
seconds = seconds - 1;
if (seconds < 0) {
// Chnage your redirection link here
window.location = "https://google.com";
} else {
// Update remaining seconds
document.getElementById("countdown").innerHTML = seconds;
// Count down using javascript
window.setTimeout("countdown()", 1000);
}
}
// Run countdown function
countdown();
</script>