瀏覽器對象模型 (BOM) 使 JavaScript 有能力與瀏覽器“對話”。
window
- 所有的瀏覽器都支持windou對象,他表示瀏覽器的窗口
- 所有 JavaScript 全局對象、函數以及變量均自動成為 window 對象的成員。
- 全局變量是 window 對象的屬性。
- 全局函數是 window 對象的方法。
- HTML DOM 的 document 也是 window 對象的屬性之一
下面的代碼顯示瀏覽器窗口的高度和寬度,不包括工具欄/滾動條。
var width =window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var height =window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
另外一些操作
window.open()
- 打開新窗口
window.close()
- 關閉當前窗口
window.moveTo()
- 移動當前窗口
window.resizeTo()
- 調整當前窗口的尺寸
Screen
screen.availWidth
- 可用的屏幕寬度
screen.availHeight
- 可用的屏幕高度
Location
window.location 對象用于獲得當前頁面的地址 (URL),并把瀏覽器重定向到新的頁面。
location.hostname
返回 web 主機的域名
location.pathname
返回當前頁面的路徑和文件名
location.port
返回 web 主機的端口 (80 或 443)
location.protocol
返回所使用的 web 協議(http:// 或 https://)
location.href
返回當前頁面的 URL
location.pathname
返回 URL 的路徑名
location.assign()
這個方法加載新的文檔
History
window.history 對象在編寫時可不使用 window 這個前綴。
history.back()
- 與在瀏覽器點擊后退按鈕相同
history.forward()
- 與在瀏覽器中點擊按鈕向前相同
Navigator
window.navigator 對象包含有關訪問者瀏覽器的信息,window.navigator 對象在編寫時可不使用 window 這個前綴。
警告:來自 navigator 對象的信息具有誤導性,不應該被用于檢測瀏覽器版本,這是因為:
navigator 數據可被瀏覽器使用者更改
瀏覽器無法報告晚于瀏覽器發布的新操作系統
消息框
alert 是警示框、可以使用“\n”來使警示語進行折行。
confirm 是確認框,用于使用戶可以驗證或者接受某些信息。
prompt("文本","默認值") 是提示框, 第二個引號中的內容是默認值 也就是占位語。
計時事件
計時時間的作用就是我們可以使用js來設定一個經過一段時間之后才執行的事件,而不是調用的時候就直接執行。
在JavaScritp 中使用計時事件有兩個關鍵方法
setTimeout("js語句",ms)
未來的某時執行代碼,第一個參數是要執行的js代碼,第二個參數是以毫秒為單位的時間。
注:1000ms = 1s。clearTimeout()
取消setTimeout()
取消計時時間的寫法為:
var t = setTimeout("alert("哈哈")",5000);
clearTimeout(t);
Cookies
cookie 用來識別用戶。cookie 是存儲于訪問者的計算機中的變量。每當同一臺計算機通過瀏覽器請求某個頁面時,就會發送這個 cookie。你可以使用 JavaScript 來創建和取回 cookie 的值。
<html>
<head>
<script type="text/javascript">
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=")
if (c_start!=-1)
{
c_start=c_start + c_name.length+1
c_end=document.cookie.indexOf(";",c_start)
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end))
}
}
return ""
}
function setCookie(c_name,value,expiredays)
{
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : "; expires="+exdate.toGMTString())
}
function checkCookie()
{
username=getCookie('username')
if (username!=null && username!="")
{alert('Welcome again '+username+'!')}
else
{
username=prompt('Please enter your name:',"")
if (username!=null && username!="")
{
setCookie('username',username,365)
}
}
}
</script>
</head>
本文內容學習自W3School,侵刪。。。