BOM概述
BOM使得JavaScript能與瀏覽器進行“對話”
主要是Window對象的操作:
⚫History對象 ⚫Location對象 ⚫Document對象
Window對象
Window對象表示瀏覽器中打開的窗口
特點:
1.Window 對象是全局對象,可直接調用其方法和屬性
2.Window對象的一些方法和屬性可省略不寫
常用屬性:
history屬性
history屬性就是History對象的引用
方法:
- back():加載上一個瀏覽的文檔
- forward():加載下一個瀏覽過的文檔
- go(n):n爲整數,跳轉第n個瀏覽過的文檔
- n==0 則刷新當前頁面
- n>0 則向前跳轉到第n個文檔
- n<0 則向後跳轉到第n個文檔
<html>
<head>
<title>history對象</title>
</head>
<body>
<h1 id="hh1">返回上一頁</h1>
<script>
//1 獲取元素
var hh1 = document.getElementById("hh1");
//2 操作元素
hh1.onclick=function(){
history.back();
}
</script>
</body>
</html>
location屬性
location屬性就是Location對象的引用
<html>
<head>
<title>location對象</title>
</head>
<body>
<input type="text" id="address" /><input type="button" value="跳轉" id="btn" />
<!-- file:///C:/Users/naixi/Desktop/www.baidu.com -->
<script type="text/javascript">
//console.log(location);
//1 獲取元素
var add=document.getElementById("address");
var btn1=document.getElementById("btn");
//2 操作元素
btn1.onclick=function(){
//console.log(location);
// 2.1 獲取文本框中的內容
var a = add.value;
// 2.2 將文本框中的內容作爲瀏覽器中的地址
location.href="https://"+a;
}
</script>
</body>
</html>
document屬性
每個載入瀏覽器的 HTML 文檔都會成爲 Document 對 象,利用它可對 HTML頁面中的所有元素進行訪問
常用屬性:
title:返回或設置當前文檔的標題
常用方法 :
◼write():向文檔寫HTML表達式或JavaScript代碼
◼getElementById():返回對擁有指定id的第一個對象的引用
◼getElementsByTagName():返回帶有指定名稱的對象集合
◼getElementsByName():返回帶有指定名稱的對象集合
實例:
<html>
<head>
<title>document對象</title>
</head>
<body>
<ul>
<li name="ll1">蘋果</li>
<li>葡萄</li>
<li name="ll1">西瓜</li>
</ul>
<script>
//1 獲取元素
var lis = document.getElementsByTagName("li");
var names = document.getElementsByName("ll1");
//2 操作元素
lis[2].innerHTML="橘子";
for(var i=0;i<lis.length;i++){
console.log(lis[i].innerHTML);
}
</script>
</body>
</html>
Window對象的常用方法
open()方法
open() 方法用於打開一個新的瀏覽器窗口或查 找一個已命名的窗口
語法:
newWIn = window.open("彈出窗口的url", "窗口名稱", "窗口特徵")
示例:
var newWin = window.open(
"adv.html",
"廣告",
" height=380, width=320, toolbar=0, scrollbars=0, location=0, status=0,menubar=0, resizable=0 "
);
窗口屬性:
close()方法
close() 方法用於關閉瀏覽器窗口
示例:
//新開一個窗口
myWindow=window.open('','','width=200,height=100')
myWindow.document.write("This is 'myWindow'");
//關閉窗口 myWindow.close();
注意:
1、某個窗口可以通過調用 self.close() 或只調用 close() 來關閉其自身 2、只有通過 JavaScript
代碼打開的窗口才能夠由 JavaScript 代碼關閉
定時函數
setInterval( fn,millisec )方法
可按照指定的週期(以毫秒計)來調用函數或計算表 達式,循環執行多次。
setTimeout( fn,millisec )方法
用於在指定的毫秒數後調用函數或計算表達式,只執行一次。
示例
//開啓一個定時函數
var n = 0; function fn() { document.title = n++; }
var timer = setInterval("fn()",1000);
定時函數的不同寫法
//函數
var n = 0;
function fn( ) { document.title = n++; }
//方法1:
var timer = window.setInterval( "fn()" , 1000);
//方法2:
var timer = window.setInterval( fn , 1000 );
//方法3:
var timer = window.setInterval( function(){//或以匿名函數作爲參數
fn()
}, 1000);
定時清除函數
clearInterval( timer ) 方法
可取消由 setInterval() 設置的 timeout
clearTimeout( timer ) 方法
可取消由 setTimeout() 方法設置的 timeout