location对象
window对象给我们提供了一个location属性用于获取或设置窗口URL,并且可以用于解析URL.因为这个属性返回的是一个对象,所有我们将这个属性也称为location对象。
URL
统一资源定位系统(uniform resource locator;URL)是因特网的万维网服务程序上用于指定信息位置的表示方法,是互联网上标准资源的地址。互联网上的每个文件都有一个唯一的URL,它包含的信息指出文件的位置以及游览器应该怎么样处理它。
location对象的属性
location.href
直接输出:得到当前页面URL
重新赋值:跳转到指定页面
案例:五秒钟后,页面自动跳转
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div></div>
<script>
// 五秒钟之后,自动跳转到指定页面
var div = document.querySelector('div');
var time = 5;
setInterval(function () {
if (time == 0) {
location.href = 'https://www.bilibili.com/'; // 对location.href重新赋值 可以让页面跳转
} else {
div.innerHTML = time + '秒钟之后,页面自动跳回bilibili';
time--;
}
}, 1000);
</script>
</body>
</html>
location.search
案例:获取URL参数(数据在不同页面传递)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<!--写一个表单 用于往另外一个页面传递数据-->
<form action="index.html"> <!--action:表单收集到的数据 将要提交到的地址-->
<input type="text" name="username">
<button>登陆</button>
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<div></div>
<script>
// location.search 返回login页面输入的参数 ?username=andy
// 1.去掉 ? 采用substring() 方法返回一个字符串在开始索引到结束索引之间的一个子集, 或从开始索引直到字符串的末尾的一个子集。
var param=location.search.substring(1); // username=andy
// 2.去掉 = 采用split('=')
var arr=param.split('='); // ["username", "andy"]
var div=document.querySelector('div');
div.innerHTML=arr[1]+',欢迎您';
</script>
</body>
</html>
location对象的方法
Location.assign()
跟href一样,可以跳转页面(也称为重定向页面)记录浏览历史,所以可以实现后退功能
location.replace()
替换当前页面,因为不记录历史,所以不能后退页面
location.reload()
重新加载页面,当对于刷新按钮或者f5 如果参数为true 相当于强制刷新或者Ctrl+5
navigator 对象
navigator对象包含有关游览器的信息,它有很多属性,我们常最常用的是useAget,该属性可以返回由客户机断送服务器的user-agent头部的值
下面的前端代码可以判断用户使用什么终端打开页面,实现跳转
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 = ""; // 手机 ""中放入手机端需要跳转到的网址
}else{
window.location.href = ""; // 电脑
}
history对象的方法
Manipulating the browser history
window.history.back()
在history中向后跳转,这和用户点击浏览器回退按钮的效果相同。
window.history.forward()
在history中向前跳转,这和用户点击浏览器前进按钮的效果相同。
window.history.go()
你可以用 go() 方法载入到会话历史中的某一特定页面, 通过与当前页面相对位置来标志 (当前页面的相对位置标志为0).
向后移动一个页面 (等同于调用 back()):
window.history.go(-1);