瀏覽器對象模型 (BOM) 使 JavaScript 有能力與瀏覽器"對話"。
瀏覽器對象模型 (BOM)
indow 尺寸
有三種方法能夠確定瀏覽器窗口的尺寸。
對于Internet Explorer、Chrome、Firefox、Opera 以及 Safari:
window.innerHeight - 瀏覽器窗口的內部高度(包括滾動條)
window.innerWidth - 瀏覽器窗口的內部寬度(包括滾動條)
對于 Internet Explorer 8、7、6、5:
document.documentElement.clientHeight
document.documentElement.clientWidth
或者
document.body.clientHeight
document.body.clientWidth
實用的 JavaScript 方案(涵蓋所有瀏覽器):
var w=window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var h=window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
其他 Window 方法
window.open() - 打開新窗口
window.close() - 關閉當前窗口
window.moveTo() - 移動當前窗口
window.resizeTo() - 調整當前窗口的尺寸
Window Screen
對象包含有關用戶屏幕的信息
screen.availWidth - 可用的屏幕寬度
screen.availHeight - 可用的屏幕高度
Window Location
用于獲得當前頁面的地址 (URL),并把瀏覽器重定向到新的頁面
location.hostname 返回 web 主機的域名
location.pathname 返回當前頁面的路徑和文件名
location.port 返回 web 主機的端口 (80 或 443)
location.protocol 返回所使用的 web 協(xié)議(http:// 或 https://)
location.href 屬性返回當前頁面的 URL。
<script>
document.write(location.href);
</script>
Window History
包含瀏覽器的歷史
history.back() - 與在瀏覽器點擊后退按鈕相同
history.forward() - 與在瀏覽器中點擊向前按鈕相同
history.go() 這個方法來實現(xiàn)向前,后退的功能
function a(){
history.go(1); // go() 里面的參數(shù)表示跳轉頁面的個數(shù) 例如 history.go(1) 表示前進一個頁面
}
function b(){
history.go(-1); // go() 里面的參數(shù)表示跳轉頁面的個數(shù) 例如 history.go(-1) 表示后退一個頁面
}
window.navigator 對象包含有關訪問者瀏覽器的信息。
三種消息框:警告框、確認框、提示框。
警告框
alert("你好,我是一個警告框!")
確認框
確認框通常用于驗證是否接受用戶操作。
當確認卡彈出時,用戶可以點擊 "確認" 或者 "取消" 來確定用戶操作。
當你點擊 "確認", 確認框返回 true, 如果點擊 "取消", 確認框返回 false。
var r=confirm("按下按鈕");
if (r==true)
{
x="你按下了\"確定\"按鈕!";
}
else
{
x="你按下了\"取消\"按鈕!";
}
提示框
var person=prompt("請輸入你的名字","Harry Potter");
if (person!=null && person!="")
{
x="你好 " + person + "! 今天感覺如何?";
document.getElementById("demo").innerHTML=x;
}
換行
彈窗使用 反斜杠 + "n"(\n) 來設置換行。
alert("Hello\nHow are you?");
計時事件
setInterval() - 間隔指定的毫秒數(shù)不停地執(zhí)行指定的代碼。
setTimeout() - 在指定的毫秒數(shù)后執(zhí)行指定代碼。
注意: setInterval() 和 setTimeout() 是 HTML DOM Window對象的兩個方法。
//每三秒彈出 "hello" :
setInterval(function(){alert("Hello")},3000);
//clearInterval() 方法用于停止 setInterval() 方法執(zhí)行的函數(shù)代碼
等待3秒,然后彈出 "Hello":
setTimeout(function(){alert("Hello")},3000);
clearTimeout() 方法用于停止執(zhí)行setTimeout()方法的函數(shù)代碼。
JavaScript Cookie
ookie 是一些數(shù)據(jù), 存儲于你電腦上的文本文件中。
當 web 服務器向瀏覽器發(fā)送 web 頁面時,在連接關閉后,服務端不會記錄用戶的信息。
當用戶訪問 web 頁面時,他的名字可以記錄在 cookie 中。
在用戶下一次訪問該頁面時,可以在 cookie 中讀取用戶訪問記錄。