location對象
什么是 location 對象
URL
location 對象的屬性
案例:5秒鐘自動跳轉(zhuǎn)頁面
<button>點(diǎn)擊</button>
<div></div>
<script>
var btn = document.querySelector('button');
var div = document.querySelector('div');
btn.addEventListener('click', function() {
// console.log(location.href);
location.href = '網(wǎng)頁地址';
})
var timer = 5;
setInterval(function() {
if (timer == 0) {
location.href = '網(wǎng)頁地址';
} else {
div.innerHTML = '您將在' + timer + '秒鐘之后跳轉(zhuǎn)到首頁';
timer--;
}
}, 1000);
</script>
案例:獲取URL參數(shù)
第一個頁面
<body>
<form action="index.html">
用戶名: <input type="text" name="uname">
<input type="submit" value="登錄">
</form>
</body>
第二個頁面index.html
<body>
<div></div>
<script>
console.log(location.search); // ?uname=andy
// 1.先去掉? substr('起始的位置'遍坟,截取幾個字符);
var params = location.search.substr(1); // uname=andy
console.log(params);
// 2. 利用=把字符串分割為數(shù)組 split('=');
var arr = params.split('=');
console.log(arr); // ["uname", "第一個頁面的輸入內(nèi)容"]
var div = document.querySelector('div');
// 3.把數(shù)據(jù)寫入div中
div.innerHTML = arr[1] + '歡迎您';
</script>
</body>
location對象的常見方法
<button>點(diǎn)擊</button>
<script>
var btn = document.querySelector('button');
btn.addEventListener('click', function() {
// 記錄瀏覽歷史拳亿,所以可以實(shí)現(xiàn)后退功能
// location.assign('網(wǎng)頁地址');
// 不記錄瀏覽歷史,所以不可以實(shí)現(xiàn)后退功能
// location.replace('網(wǎng)頁地址 ');
//強(qiáng)制刷新(true)
location.reload(true);
})
</script>
navigator對象
? navigator 對象包含有關(guān)瀏覽器的信息愿伴,它有很多屬性肺魁,我們最常用的是 userAgent,該屬性可以返回由客戶機(jī)發(fā)送服務(wù)器的 user-agent 頭部的值隔节。
下面前端代碼可以判斷用戶那個終端打開頁面鹅经,實(shí)現(xiàn)跳轉(zhuǎn)
if((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
window.location.href = ""; //手機(jī)
} else {
window.location.href = ""; //電腦
}
history對象
? window對象給我們提供了一個 history對象寂呛,與瀏覽器歷史記錄進(jìn)行交互。該對象包含用戶(在瀏覽器窗口中)訪問過的URL瘾晃。
history對象一般在實(shí)際開發(fā)中比較少用贷痪,但是會在一些 OA 辦公系統(tǒng)中見到。