JavaScript 頁面常見操作:跳轉(zhuǎn)、刷新、關(guān)閉

注意:window 對(duì)象變量可以省略 window,直接使用變量,但是建議加上 window

1. window.location

  1. 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");
  1. 刷新頁面
    重新加載當(dāng)前頁面
window.location.reload()
  1. 獲取和設(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();
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容