提供了与当前窗口中加载的文档有关的信息,还提供了一些导航的功能,它既是window对象的属性也是document对象的属性。
属性:
location.href 返回当前加载页面的完整URL 说明:location.href与window.location.href等价
console.log(location.href);//http://localhost:63342/Demo/location.html
location.hash 返回URL中的hash(#号后 跟零或多个字符),如果不包含则返回空字符串。锚点。
<style>
.box1{height: 400px;background: #ccc;}
.box2{height: 600px;background: #666;}
</style>
</head>
<body>
<div class="box1" id="top"></div>
<div class="box2"></div>
<input type="button" id="btn" value="返回顶部"/>
<script>
console.log(location.hash);
var btn=document.getElementById("btn");
btn.onclick=function(){
location.hash="#top";
}
</script>
点击返回顶部的按钮返回浏览器顶部。
location.host:返回服务器名称和端口号
location.hostname:返回不带端口号的服务器名称
location.pathname:返回URL中的目录和(或)文件名。
location.port:返回URL中指定的端口号,如果没有,返回空字符串。
location.protocol:返回页面使用的协议。
location.search:返回URL的查询字符串。这个字符串以问号开头。
位置操作:
改变浏览器位置的方法:location.href属性
location对象其他属性也可改变URL:location.hash location.search
location.replace(url):重新定向URL。不会再历史记录中生成新记录。
<script>
setTimeout(function(){
//会跳转到location.html,并且浏览器会产生记录(按后退键返回原来页面)。如果不想产生记录用replace()
// location.href='location.html'; // window.location='location.html'
location.replace('location.html');
},1000)
</script>
location.reload() 重新加载当前显示的页面。重新加载页面。
说明:
- location.reload()有可能从缓存中加载
- location.reload(true)从服务器重新加载
建议将reload代码放在最后一行。因为reload是做刷新的操作
document.getElementById("reload").onclick=function(){
// location.reload();//从缓存中刷新
location.reload(true);//强制从服务器刷新
}