一、BOM簡介
BOM(Browser Object Model)即浏覽器對象模型,它提供了獨立于内容而與浏覽器視窗進行互動的對象,其核心對象是 window。
Window 對象
window對象是浏覽器的頂級對象。表示浏覽器中打開的視窗。
window對象是一個全局對象。定義在全局作用域中的變量、函數都自動成為 window 對象的屬性和方法。
- window 對象中的主要屬性:确定浏覽器視窗的尺寸
- window 對象中的主要方法:
- 打開/關閉視窗的控制方法
- 各種操作彈框
- window 對象中的主要子對象:
- Screen螢幕
- Location獲得目前頁面的url位址
- History曆史
- Navigator浏覽器資訊
二、window 對象的主要屬性
确定浏覽器視窗尺寸
浏覽器的視口,不包括工具欄和滾動條。
有三種方法能夠确定浏覽器視窗的尺寸:
方法一
對于Internet Explorer、Chrome、Firefox、Opera 以及 Safari:
window.innerWidth - 浏覽器視窗的内部寬度
window.innerHeight - 浏覽器視窗的内部高度
var w = window.innerWidth; // 浏覽器視窗的内部寬度
var h = window.innerHeight; // 浏覽器視窗的内部高度
var h2 = document.querySelector('h2');
h2.innerHTML = 'window.innerWidth:' + w + '<br>' + 'window.innerHeight:' + h;
方法二
對于 Internet Explorer 5/6/7/8:(client:客戶)
document.documentElement.clientWidth
document.documentElement.clientHeight
var w_2 = document.documentElement.clientWidth;
var h_2 = document.documentElement.clientHeight;
var new2 = document.createElement('h4'); // 建立元素節點 h4
new2.innerHTML = 'document.documentElement.clientWidth:' + w_2 + '<br>' + 'document.documentElement.clientHeight:' + h_2; // 給建立的節點h4指派
h2.appendChild(new2); // 父級h2上面已經擷取過了 在父節點h2的末尾追加h4
方法三
對上面的簡寫 獲得的是body的寬高(沒有給寬高時由内容撐開)
document.body.clientWidth
document.body.clientHeight
var w_3 = document.body.clientWidth;
var h_3 = document.body.clientHeight;
var h3 = document.querySelector('h3');
h3.innerHTML = 'document.body.clientWidth:' + w_3 + '<br>' + 'document.body.clientHeight:' + h_3;
三、window 對象的主要方法
1. 打開視窗 window.open()
window.open(URL,name,features,replace)
- URL:一個可選的字元串,聲明了要在新視窗中顯示的文檔的 URL
- name:一個可選的字元串,該字元聲明了新視窗的名稱,這個名稱可以用作标記 a 和 form 的屬性 target 的值。
- features:一個可選的字元串,聲明了新視窗要顯示的标準浏覽器的特征
- replace:一個可選的布爾值。true - URL 替換浏覽曆史中的目前條目。false - URL 在浏覽曆史中建立新的條目。
<button onclick="opentest1();">打開新的視窗</button>
function opentest1() {
// window.open('01-test.html', 'test1', 'width=500,height=500', false);
window.open('01-test.html'); // 後三個參數可選 一般寫新頁面的url參數即可
// window.open('http://www.baidu.com/');
}
2. 關閉視窗 window.close()
window.close() 方法用于關閉浏覽器視窗。無參數
<button onclick="closethis();">關閉目前視窗</button>
function closethis() {
window.close();
}
3. 警告框 alert()
警告框經常用于確定使用者可以得到某些資訊。
當警告框出現後,使用者需要點選确定按鈕才能繼續進行操作。
文法:window.alert(“sometext”);
可以不帶上window對象,直接使用 alert() 方法
<button onclick="testalert();">alert警告框</button>
<script>
function testalert() {
alert('測試警告框');
}
</script>
4. 确認框 confirm()
确認框通常用于驗證是否接受使用者操作。
當确認卡彈出時,使用者可以點選 “确認” 或者 “取消” 來确定使用者操作。
當你點選 “确認”, 确認框傳回 true, 如果點選 “取消”, 确認框傳回 false。
文法:window.confirm(“sometext”);
可以不帶上window對象,直接使用 confirm() 方法
<button onclick="testconfirm();">confirm确認框</button>
<script>
function testconfirm() {
var flag = window.confirm('确認要關閉嗎?'); // 當點選确認/取消時,會傳回t/f
if (flag) { // 當傳回值為true時,即客戶點選了确認,則關閉目前頁面
window.close();
}
}
</script>
5. 提示框
提示框經常用于提示使用者在進入頁面前輸入某個值。
當提示框出現後,使用者需要輸入某個值,然後點選确認或取消按鈕才能繼續操縱。
如果使用者點選确認,那麼傳回值為輸入的值。如果使用者點選取消,那麼傳回值為 null。
文法:window.prompt(“sometext”,“defaultvalue”);
可以不帶上window對象,直接使用 prompt() 方法
<button onclick="testprompt()">prompt提示框</button>
<script>
function testprompt() {
var msg = window.prompt('請輸入姓名:', 'admin'); // admin為預設值
if (msg != null && msg != 'admin') { // 當輸入值不為空,且不是預設值時,在彈出框中顯示出使用者輸入的值
window.alert('您的姓名是:' + msg);
}
}
</script>
練習案例:猜數字遊戲
<button onclick="play()">開始猜數字遊戲</button>
<script>
function play() {
var num = parseInt(Math.random() * 100 + 1); // 獲得一個随機整數
do {
var num1 = prompt('請輸入1~100之間的一個整數');
if (num1 < num) {
alert('猜小了');
} else if (num1 > num) {
alert('猜大了');
} else {
alert('恭喜您,猜對了!');
}
} while (num1 != num);
}
</script>
四、window 對象的主要子對象
1. Screen 螢幕
window.screen 對象包含有關使用者螢幕的資訊。
在編寫時可以不使用 window 這個字首。
有以下屬性:
1)總寬度和總高度 screen.width / screen.height
是整個螢幕的寬和高,差別與浏覽器視口寬高,螢幕大小尺寸不會随着浏覽器視窗調整大小而變化。
<p id="p1"></p>
<script>
var p1 = document.getElementById('p1');
var totlew = window.screen.width;
var totleh = window.screen.height;
p1.innerHTML = '總寬度screen.width為:' + totlew + ' , ' + '總高度screen.height為:' + totleh;
</script>
2)可用寬度和可用高度 screen.availWidth / screen.availHeight
可用寬度 / 高度不包括配置設定給半永久特性(如螢幕底部的工作列)的垂直空間。
<p id="p2"></p>
<script>
var p2 = document.getElementById('p2');
var availw = window.screen.availWidth;
var availh = window.screen.availHeight;
p2.innerHTML = '可用寬度screen.availWidth為:' + availw + ' , ' + '可用高度screen.availHeight為:' + availh;
</script>
3)色彩深度 screen.colorDepth
colorDepth 屬性傳回目标裝置或緩沖器上的調色闆的比特深度。
<p id="p3"></p>
<script>
var p3 = document.getElementById('p3');
var colorDepth = window.screen.colorDepth;
p3.innerHTML = '色彩深度screen.colorDepth為:' + colorDepth;
</script>
4)色彩分辨率 screen.pixelDepth
pixelDepth 屬性傳回顯示螢幕的顔色分辨率(比特每像素)。
<p id="p4"></p>
<script>
var p4 = document.getElementById('p4');
var pixelDepth = window.screen.pixelDepth;
p4.innerHTML = '色彩分辨率screen.pixelDepth為:' + pixelDepth;
</script>
2. Location 獲得目前頁面的url位址
window.location 對象用于獲得目前頁面的位址 (URL),并把浏覽器重定向到新的頁面。
window.location 對象在編寫時可不使用 window 這個字首。
URL
統一資源定位符(Uniform Resource Locator)是網際網路上标準資源的位址。網際網路上的每個檔案都有一個唯一的URL,它包含的資訊指出檔案的位置以及浏覽器應該怎麼處理它。
window.location 對象的2個屬性:
1)location.href
location.href 屬性傳回目前頁面的 URL。
<button onclick="testHref();">點選查詢目前頁面的URL</button>
<script>
function testHref() {
var url1 = window.location.href;
var flag = confirm('目前頁面的URL位址為:' + url1 + '\n' + '是否要跳轉至新頁面?')
if (flag) {
window.location.href = 'success.html';
}
}
</script>
2)location.search
location.search 屬性是一個可讀可寫的字元串,可設定或傳回目前 URL 的查詢部分(問号 ? 之後的部分)。
<input type="text" id="uname">
<input type="password" id="psd">
<button onclick="login();">登入</button>
<script>
function login() {
var unamobj = document.getElementById('uname'); // 得到使用者名文本框
var uname = unamobj.value; // 得到使用者名文本框裡的值
var psdobj = document.getElementById('psd'); // 得到密碼框
var psd = psdobj.value; // 得到密碼框裡的值
// 當使用者名和密碼為給定的值時,攜帶該值跳轉到success頁面
if (uname == 'zhangsan' && psd == '123456') {
window.location.href = 'success.html?uname=' + uname + '&psd=' + psd;
} else { // 否則提示錯誤,并清空使用者名和密碼輸入框
window.alert('使用者名密碼輸入有誤,請重新輸入!');
unamobj.value = '';
psdobj.value = '';
}
}
</script>
在登入成功的頁面顯示使用者名:
<h1></h1>
<script>
window.onload = function () {
// location.search問号?之後的部分(包含?問号)
var query = window.location.search;
// console.log(query); // ?uname=zhangsan&psd=123456
var infoArray = query.split('&'); // split把字元串分割為字元串數組
// console.log(infoArray); // ['?uname=zhangsan', 'psd=123456']
var uname = '';
var psd = '';
for (var k in infoArray) {
var info = infoArray[k]; // for in 循環拿到的是下标 用索引号拿到字元串對象
var msgArray = info.split('='); // 用=号把鍵值對割開
if (msgArray[0] == '?uname') {
uname = msgArray[1];
}
if (msgArray[0] == 'psd') {
psd = msgArray[1];
}
}
// 得到h1對象 并向h1裡面寫入内容
var h1 = document.querySelector('h1');
h1.innerHTML = uname + ',登陸成功!您輸入的密碼是:' + psd;
}
</script>
3. History 曆史
window.history 對象包含浏覽器的URL曆史。
在編寫時可不使用 window 這個字首。
方法:
1)history.back()
history.back() 方法加載曆史清單中的前一個 URL。這與在浏覽器中點選後退按鈕是相同的
2)history forward()
history forward() 方法加載曆史清單中的下一個 URL。這與在浏覽器中點選前進按鈕是相同的
第一個頁面:中間頁面:<h1>071-test.html</h1> <a href="072-test.html">跳轉至下一頁</a> <button onclick="testforward();">==></button> <script> function testforward() { window.history.forward(); } </script>
最後一個頁面:<a href="071-test.html">跳轉至上一頁</a> <button onclick="testback();">上一頁</button> <script> function testback() { window.history.back(); } </script> <a href="073-test.html">跳轉至下一頁</a> <button onclick="testforward();">下一頁</button> <script> function testforward() { window.history.forward(); } </script>
<h1>073-test.html</h1> <button onclick="testback();"><== </button> <script> function testback() { window.history.back(); } </script>
4. Navigator 浏覽器資訊
document.write("<h1>浏覽器代号:" + window.navigator.appCodeName + "</h1>");
document.write("<h1>浏覽器名稱:" + window.navigator.appName + "</h1>");
document.write("<h1>浏覽器版本:" + window.navigator.appVersion + "</h1>");
document.write("<h1>啟用Cookies:" + window.navigator.cookieEnabled + "</h1>");
document.write("<h1>硬體平台:" + window.navigator.platform + "</h1>");
document.write("<h1>使用者代理:" + window.navigator.userAgent + "</h1>");
document.write("<h1>使用者代理語言:" + window.navigator.systemLanguage + "</h1>");
五、計時事件
window 對象給我們提供了 2 個非常好用的方法——定時器。
- setTimeout()
- setInterval()
1. setInterval()
間隔指定的毫秒數不停地執行指定的代碼
文法:setInterval(“javascript function”,milliseconds);
- 參數1 —— 函數(function)
- 參數2 —— 間隔的毫秒數(1000 毫秒是一秒)
clearInterval()
用于停止 setInterval() 方法執行的函數代碼
文法:clearInterval(intervalVariable)
- intervalVariable參數 是 setInterval() 的傳回值
<h1 id="time"></h1>
<button onclick="stop();">停止計時</button>
<script>
// 建立事件日期對象
function getDate() {
var date1 = new Date();
var y = date1.getFullYear();
var m = date1.getMonth() + 1;
m = m < 10 ? '0' + m : m;
var d = date1.getDate();
d = d < 10 ? '0' + d : d;
var h = date1.getHours();
h = h < 10 ? '0' + h : h;
var min = date1.getMinutes();
min = min < 10 ? '0' + min : min;
var s = date1.getSeconds();
s = s < 10 ? '0' + s : s;
timestr = y + '年' + m + '月' + d + '日 ' + h + '時' + min + '分' + s + '秒';
document.querySelector('#time').innerHTML = timestr;
}
var res;
window.onload = function () {
res = setInterval(function () {
getDate();
}, 1000)
}
function stop() {
clearInterval(res);
}
</script>
2. setTimeout()
間隔指定的毫秒數執行指定的代碼一次
文法:setTimeout(“javascript function”, milliseconds);
- 參數1 —— 函數(function)
- 參數2 —— 間隔的毫秒數(1000 毫秒是一秒)
clearTimeout()
用于停止執行setTimeout()方法的函數代碼。
文法:clearTimeout(timeoutVariable)
- intervalVariable參數 是 setTimeout() 的傳回值
<p>點選按鈕,在等待 3 秒後彈出 "Hello"。</p>
<button onclick="hello()">點我3秒後彈出hello</button>
<button onclick="stoph()">點我停止彈框</button>
<script>
var myvar;
function hello() {
myvar = setTimeout(function () {
alert('hello!')
}, 3000);
}
function stoph() {
clearTimeout(myvar);
}
</script>