浏览器窗口和文档的定位高手:Window.location
2023-04-05 09:33:48
Window.location:操控浏览器窗口和文档定位
简介
JavaScript 中的 Window.location 对象是一个强大的工具,用于操控浏览器窗口和文档定位。它允许你跳转页面、传递参数、加载文档,以及访问和修改有关当前页面和窗口的各种信息。
访问当前 URL
Window.location.href 属性存储当前页面的完整 URL。你可以使用它来检索当前位置或生成书签。
跳转页面
要跳转到新页面,只需将新的 URL 分配给 Window.location.href。例如:
Window.location.href = "https://example.com";
传递参数
在 URL 中添加查询字符串参数,可以将数据从一个页面传递到另一个页面。例如:
Window.location.href = "https://example.com?name=John&age=30";
刷新页面
Window.location.reload() 方法可重新加载当前页面。
停止加载
如果页面正在加载,Window.location.stop() 方法会停止加载过程。
获取协议、主机和端口
Window.location 对象提供了获取当前页面协议、主机名和端口号的属性:
Window.location.protocol; // 获取协议(例如:http、https)
Window.location.hostname; // 获取主机名
Window.location.port; // 获取端口号
获取路径和文件名
Window.location.pathname 和 Window.location.filename 属性可以获取路径和文件名:
Window.location.pathname; // 获取路径(不包含文件名)
Window.location.filename; // 获取文件名(不包含路径)
获取查询字符串和参数
Window.location.search 属性存储查询字符串,Window.location.searchParams 属性提供一个参数对象:
Window.location.search; // 获取查询字符串(?后面的部分)
Window.location.searchParams; // 获取 URL 参数对象
修改哈希值
Window.location.hash 属性存储哈希值。你可以使用它来修改哈希值或跳转到文档中的特定部分:
Window.location.hash = "#section-2";
监听 URL 变化
你可以使用 window.addEventListener("hashchange", function()) 来监听哈希值的变化。
安全跳转
Window.location.replace() 方法允许安全跳转到新页面,不会在历史记录中留下旧页面:
Window.location.replace("https://example.com");
获取当前页面的绝对路径
Window.location.origin 属性存储当前页面的绝对路径,包括协议、主机名和端口:
Window.location.origin; // 获取当前页面的绝对路径
跨域跳转
Window.open("https://example.com", "_blank") 方法可在新窗口中打开跨域页面。
获取当前窗口的对象
Window.self 属性返回当前窗口的对象。
获取父窗口的对象
Window.parent 属性返回父窗口的对象。
获取顶层窗口的对象
Window.top 属性返回顶层窗口的对象。
判断是否在 iframe 中
你可以使用 Window.self !== Window.top 来判断是否在 iframe 中。
获取当前窗口的尺寸
Window.innerWidth 和 Window.innerHeight 属性存储当前窗口的内部宽度和高度。
获取滚动条的位置
Window.scrollX 和 Window.scrollY 属性存储水平和垂直滚动条的位置。
滚动到指定位置
Window.scrollTo(x, y) 方法可滚动到指定位置。
滚动到页面底部
Window.scrollTo(0, document.body.scrollHeight); // 滚动到页面底部
添加自定义数据
Window.location.assign() 方法允许在 URL 中添加自定义数据:
Window.location.assign("https://example.com#section-2");
移除哈希值
Window.location.hash = ""; // 移除哈希值
获取 Referrer
Window.location.referrer 属性存储 Referrer。
导航到新页面
Window.location.assign() 方法可导航到新页面。
导航到上一个页面
Window.location.back() 方法可导航到上一个页面。
导航到下一个页面
Window.location.forward() 方法可导航到下一个页面。
创建新的 History 条目
Window.location.pushState() 方法创建新的 History 条目:
Window.location.pushState({page: 1}, "Page 1", "page1.html");
替换当前的 History 条目
Window.location.replaceState() 方法替换当前的 History 条目:
Window.location.replaceState({page: 2}, "Page 2", "page2.html");
监听 History 变化
window.addEventListener("popstate", function()) 监听 History 变化。
常见问题解答
-
如何获取当前页面的路径?
- 使用 Window.location.pathname。
-
如何向 URL 添加查询字符串参数?
- 使用 Window.location.search += "&name=John&age=30"。
-
如何安全跳转到新页面?
- 使用 Window.location.replace()。
-
如何判断是否在 iframe 中?
- 使用 Window.self !== Window.top。
-
如何滚动到页面底部?
- 使用 Window.scrollTo(0, document.body.scrollHeight)。