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