注意:window 對(duì)象變量可以省略 window,直接使用變量,但是建議加上 window
1. window.location
- href、assign()、replace() 跳轉(zhuǎn)頁面
href 屬性 和 assign()方法 用于跳轉(zhuǎn)頁面功能一樣,只是寫法不同,保留緩存歷史,可回退
// href 是屬性,賦值即調(diào)用
window.location.;
window.location.assign("http://www.baidu.com");
replace()方法 跳轉(zhuǎn)頁面,刪除歷史緩存,無法回退
window.location.replace("http://www.baidu.com");
- 刷新頁面
重新加載當(dāng)前頁面
window.location.reload()
- 獲取和設(shè)置當(dāng)前頁面 url 的相關(guān)信息
console.log(window.location.href); //完整url:協(xié)議名.域名:端口號(hào)/路徑/?參數(shù)#hash
console.log(window.location.protocol); // 協(xié)議號(hào)
console.log(window.location.host); //域名和端口號(hào)
console.log(window.location.hostname); //域名
console.log(window.location.port); // 域名后的端口號(hào)
console.log(window.location.pathname); // 端口號(hào)后的路徑
console.log(window.location.search); // 參數(shù) 格式:?id=1
console.log(window.location.hash); // # hash參數(shù)
2. window.history
需要有歷史緩存,才可操作
window.history.forward(); // 瀏覽器前進(jìn)
window.history.back(); // 瀏覽器后退
window.history.go(-1); // 瀏覽器后退
window.history.go(0); // 刷新頁面
window.history.go(1); // 瀏覽器前進(jìn)
window.history.go(num); // 跳轉(zhuǎn)到指定的歷史記錄頁
// 功能:切換到指定url,不重新加載頁面
// state:狀態(tài)對(duì)象可以是任何可以序列化的對(duì)象,JSON對(duì)象,(獲取方式:window.history.state)
// name:標(biāo)題名稱,瀏覽器兼容性極差,建議傳 ''
// url:新歷史記錄條目的URL,相對(duì)或者絕對(duì)路徑,不傳代表當(dāng)前頁面url(可直接傳:?參數(shù)=參數(shù)值),注意:url必須同域,否則無效
history.pushState(state, name, url);
history.replaceState(state, name, url);
console.log(window.history.length); // 獲取緩存歷史的條數(shù) 最少時(shí) 1
// 使用 pushState 和 replaceState 時(shí),調(diào)用此事件
window.addEventListener("popstate", function (e) {
const url = window.location.href;
console.log("url);
console.log(e.state); // 獲取頁面參數(shù) state 對(duì)象
});
3. window 打開和關(guān)閉新窗口
// 保留當(dāng)前頁面,打開子窗口
// url:打開子窗口的路徑
// name:打開子窗口的名稱
// 寬高:設(shè)置打開子窗口的寬高,默認(rèn)100%
// newWindow:返回子窗口的window,可對(duì)子窗口進(jìn)行操作
const newWindow = window.open(url,name,寬高);
window.open("http://www.baidu.com",'新標(biāo)題','width=200,height=100');
// 關(guān)閉當(dāng)前頁面
window.close();