<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>时间</title>
<script type="text/javascript">
var attime;
function clock(){
var time=new Date();
attime=time.getHours()+":"+time.getMinutes()+":"+time.getSeconds();
document.getElementById("clock").value = attime;
}
setInterval(clock,1000);
</script>
</head>
<body>
<form>
<input type="text" id="clock" size="50" />
</form>
</body>
</html>
也可以使用setTimeout()函数:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>时间</title>
<script type="text/javascript">
var attime;
function clock(){
var time=new Date();
attime=time.getHours()+":"+time.getMinutes()+":"+time.getSeconds();
document.getElementById("clock").value = attime;
setTimeout(clock,1000);
}
setTimeout(clock,1000);
</script>
</head>
<body>
<form>
<input type="text" id="clock" size="50" />
</form>
</body>
</html>
可以用刚才学会的计时器做一个页面返回程序,就学的过程来说,setInterval会比setTimeout函数更加好用,更加稳定,setTimeOUt函数可能会存在多个计时器导致计时速度加快,影响结果。
</pre><pre name="code" class="html"><!DOCTYPE html>
<html>
<head>
<title>浏览器对象</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<!--先编写好网页布局-->
<p>
操作成功!<br>
<input type="text" id="txt1" size="1"/>秒后返回主页面</br>
<b id="txt2"></b>秒后返回主页</br>
<a href="javascript:back()"> 返回</a>
</p>
<script type="text/javascript">
//获取显示秒数的元素,通过定时器来更改秒数。
var num=5;
function time(){
document.getElementById("txt2").innerHTML=num;
document.getElementById("txt1").value=num;
num=num-1;
if(num==0){
location.href="http://www.baidu.com";
}
}
setInterval(time,1000);
//通过window的location和history对象来控制网页的跳转。
function back(){
window.history.back();
}
</script>
</body>
</html>