本文我们用js 中的setTimeout()和 clearTimeout()方法实现倒计时效果
由于有了setTimeout()和 clearTimeout(),在JavaScritp中使用计时事件成了一件很容易的事,所以按照自己的简单想法,写了一个倒计时效果,时间到后显示一个相应的图片。
xhtml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <meta http-equiv="Content-Language" content="gb2312" /> <title>倒计时演示</title> <meta name="Author" content="jzxue(建站学), longchina@jzxue.com" /> <style type="text/css"> #t2{display:none;} </style> </head> <body> <div id="test"> <input id="t1" type="button" onclick="detonate();" value="倒计时开始" /> <input id="t2" type="button" onclick="demolite();" value="停止倒计时" /> </div> </body> </html>
javascript:
<script type="text/javascript"> var x = document.getElementById("test"); var x2 = document.getElementById("t1"); var x3 = document.getElementById("t2"); var c = 10; var timeId1 = 0; function detonate(){ x3.style.display = "inline"; x2.value = "倒计时"; x2.value += c--; if(c >= 0){ timeId1 = window.setTimeout(detonate,1000); }else{ x2.style.display = "none"; x3.style.display = "none"; bomb = document.createElement("div"); bomb.innerHTML = "<img src='1.jpg' alt='bomb' />"; document.body.appendChild(bomb); } } function demolite(){ window.clearTimeout(timeId1); x3.style.display = "none"; alert("时间到。请注意。"); x2.value = "继续"; } </script>
(责任编辑:admin) |