瀏覽器對象模型 (BOM) 使 JavaScript 有能力與瀏覽器“對話”羡洛。
window
- 所有的瀏覽器都支持windou對象垃环,他表示瀏覽器的窗口
- 所有 JavaScript 全局對象司浪、函數(shù)以及變量均自動成為 window 對象的成員茎芋。
- 全局變量是 window 對象的屬性。
- 全局函數(shù)是 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()
- 關(guān)閉當前窗口
window.moveTo()
- 移動當前窗口
window.resizeTo()
- 調(diào)整當前窗口的尺寸
Screen
screen.availWidth
- 可用的屏幕寬度
screen.availHeight
- 可用的屏幕高度
Location
window.location 對象用于獲得當前頁面的地址 (URL)陌兑,并把瀏覽器重定向到新的頁面沈跨。
location.hostname
返回 web 主機的域名
location.pathname
返回當前頁面的路徑和文件名
location.port
返回 web 主機的端口 (80 或 443)
location.protocol
返回所使用的 web 協(xié)議(http:// 或 https://)
location.href
返回當前頁面的 URL
location.pathname
返回 URL 的路徑名
location.assign()
這個方法加載新的文檔
History
window.history 對象在編寫時可不使用 window 這個前綴。
history.back()
- 與在瀏覽器點擊后退按鈕相同
history.forward()
- 與在瀏覽器中點擊按鈕向前相同
Navigator
window.navigator 對象包含有關(guān)訪問者瀏覽器的信息,window.navigator 對象在編寫時可不使用 window 這個前綴兔综。
警告:來自 navigator 對象的信息具有誤導(dǎo)性饿凛,不應(yīng)該被用于檢測瀏覽器版本狞玛,這是因為:
navigator 數(shù)據(jù)可被瀏覽器使用者更改
瀏覽器無法報告晚于瀏覽器發(fā)布的新操作系統(tǒng)
消息框
alert 是警示框、可以使用“\n”來使警示語進行折行涧窒。
confirm 是確認框心肪,用于使用戶可以驗證或者接受某些信息。
prompt("文本","默認值") 是提示框纠吴, 第二個引號中的內(nèi)容是默認值 也就是占位語硬鞍。
計時事件
計時時間的作用就是我們可以使用js來設(shè)定一個經(jīng)過一段時間之后才執(zhí)行的事件,而不是調(diào)用的時候就直接執(zhí)行戴已。
在JavaScritp 中使用計時事件有兩個關(guān)鍵方法
setTimeout("js語句",ms)
未來的某時執(zhí)行代碼膳凝,第一個參數(shù)是要執(zhí)行的js代碼,第二個參數(shù)是以毫秒為單位的時間恭陡。
注:1000ms = 1s。clearTimeout()
取消setTimeout()
取消計時時間的寫法為:
var t = setTimeout("alert("哈哈")"上煤,5000)休玩;
clearTimeout(t);
Cookies
cookie 用來識別用戶。cookie 是存儲于訪問者的計算機中的變量劫狠。每當同一臺計算機通過瀏覽器請求某個頁面時拴疤,就會發(fā)送這個 cookie。你可以使用 JavaScript 來創(chuàng)建和取回 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>
本文內(nèi)容學(xué)習(xí)自W3School呐矾,侵刪。懦砂。蜒犯。