我想给这个倒计时代码,一个onclick按钮。
当我点击按钮时,它会启动。
我该怎么做?
由于
var targetURL = "http://stackoverflow.com/"
var countdownfrom = 10
var currentsecond = document.getElementById('redirect').innerHTML = countdownfrom + 1
function countredirect() {
if (currentsecond != 1) {
currentsecond -= 1
document.getElementById('redirect').innerHTML = currentsecond
} else {
window.location = targetURL
return
}
setTimeout("countredirect()", 1000)
}
countredirect()
<span id="redirect"></span>
答案 0 :(得分:0)
请尝试以下代码:
EB
答案 1 :(得分:0)
这是一个可行的选择:
innerHTML
元素的 redirect
。> 0
减少它。0
停止 interval
。<强>代码:强>
/* ----- JavaScript ----- */
var
interval,
countdown = 10,
redir = document.getElementById("redirect"),
targetURL = "http://stackoverflow.com/",
reset = function () {
redir.innerHTML = countdown;
};
/* Set the countdown to the redirect element. */
window.onload = reset;
/* When the button is clicked... */
document.getElementById("button").onclick = function () {
var
button = this,
counter = countdown;
/* Clear the interval to start anew. */
clearInterval(interval);
this.innerHTML = "Restart";
/* The interval. */
interval = setInterval(function () {
if (counter) redir.innerHTML = --counter;
else {
clearInterval(interval);
button.innerHTML = "Start";
}
}, 1000);
/* Reset. */
reset();
}
&#13;
<!----- HTML ----->
<span id = "redirect"></span>
<button id = "button">Start</button>
&#13;