1.window對象
所有的浏覽器都支援window對象
概念上講,一個html文檔對應一個window對象
功能上講,控制浏覽器視窗
使用上講,window對象不需要建立對象,直接使用
2.window對象方法:
2.1 alert()
顯示一個帶有一段消息和一個确認按鈕的警告框
例子:
window.alert("hello world"); //在浏覽器視窗彈出一個"hello world"對話框
用浏覽器打開,顯示如下:

2.2 confirm()
顯示帶有一段消息以及确認按鈕和取消按鈕的對話框
var res=confirm("确定删除??");
window.alert(res); //浏覽器視窗彈出一個"确認删除"對話框,等待使用者選擇
2.3 prompt()
顯示可提示使用者輸入的對話框
prompt()可以使用兩個參數,第一個參數為提示資訊,第二個參數為輸入預設值,傳回值是使用者輸入的内容
例子一:
var res=prompt("Input a num:");
window.alert(res);
例子二:
var res=prompt("Input a num:","1234");
window.alert(res);
2.4 open()
打開一個新的浏覽器視窗或查找一個已經命名的視窗
可用三個參數,參數一為新打開的視窗的網址,參數二為新視窗的名字,可不填,參數三為新打開的視窗的尺寸
window.open("http://www.baidu.com");
用浏覽器打開,浏覽器會再打開一個視窗打開百度的首頁
//新打開一個寬度為300px,高度為150px的視窗,網址為百度
window.open("http://www.baidu.com","",'width=300,resizable=no,height=150');
2.5 close()
關閉浏覽器視窗
window.close(); //會關閉目前的浏覽器視窗
2.6 setInterval()
按照指定的周期(以毫秒計)來調用函數或計算表達式
setInterval()方法會不停的調用函數,直到clearInterval()被調用或視窗被關閉
由setInterval()傳回的id值可用作clearInterval()方法的參數
文法:
setInterval(code,millisec)
其中,code為要調用的函數或要執行的代碼段,millisec為周期性執行的時間間隔,機關為毫秒
2.7 clearInterval()
取消由setInterval()設定的timeout
<input id="ID1" type="text" onclick="begin()">
<button onclick="end()">停止</button>
<script>
function show_time(){
var time1=new Date().toLocaleString();
var temp=document.getElementById("ID1");
temp.value=time1;
}
var ID;
function begin(){
if (ID==undefined){
show_time();
ID=setInterval(show_time,1000);
}
}
function end(){
clearInterval(ID);
ID=undefined;
}
</script>
在輸入框中單擊,輸入框中會顯示出目前的時間,一秒鐘更新一次
顯示如下:
直到單擊停止按鈕,計時才會停止,再次單擊輸入框後,輸入框内的時間會以一秒鐘的頻率更新,直到再次單擊停止按鈕
2.8 setTimeout()
在指定的毫秒數後調用函數或計算表達式
<input type="button" value="alert_box" onclick="time_msg()">
<script>
var times;
function time_msg(){
var time1=setTimeout("window.alert('5 seconds!')",5000);
}
</script>
等待5秒鐘後,會彈出如下對話框:
<input type="text" id="txt">
<input type="button" value="start count" onclick="time_count()">
<script>
var times;
var count=0;
function time_count(){
document.getElementById("txt").value=count;
count +=1;
times=setTimeout("time_count()",1000)
}
</script>
當計時按鈕被點選後,輸入框中就從0開始計數,一秒鐘一次
如圖所示:
2.9 clearTimeout()
取消由setTimeout()方法設定的timeout
<input type="text" id="txt">
<input type="button" value="start" onclick="time_count()">
<input type="button" value="stop" onclick="stop_count()">
<script>
var times;
var count=0;
function time_count(){
document.getElementById("txt").value=count;
count +=1;
times=setTimeout("time_count()",1000)
}
function stop_count(){
clearTimeout(times);
}
生成一個計時器,單擊開始按鈕,輸入框中會開始計時,直到單擊停止按鈕才會暫停,再次單擊開始,輸入框中的秒數會從上次暫停的時間繼續計時