参考资料

  1. HTML DOM 哪个鼠标键被点击了?
  2. HTML DOM 返回图像映射的某个区域的hostname实例
  3. HTML DOM 属性
  4. HTML DOM 提交表单
  5. HTML DOM 返回一个区域的href属性的querystring部分 实例
  6. HTML DOM 被按下的键盘键的keycode?
  7. HTML DOM 返回和设置链接的charset属性实例
  8. HTML DOM 节点

HTML DOM 返回完整 URL 实例

简介

HTML DOM 提供了多种方法来获取当前文档的完整 URL,最常用的是 window.location.href 属性。

主要属性和方法

1. window.location.href

返回完整的 URL 字符串

var fullUrl = window.location.href;

2. document.URL

返回文档的完整 URL(与 window.location.href 类似)

var docUrl = document.URL;

3. window.location 对象的其他属性

  • protocol: 返回协议部分(如 http: 或 https:)

  • host: 返回主机名和端口号

  • hostname: 返回主机名

  • port: 返回端口号

  • pathname: 返回路径部分

  • search: 返回查询字符串部分

  • hash: 返回锚点部分

实例

获取完整 URL

// 获取当前页面的完整URL
var currentUrl = window.location.href;
console.log("当前URL: " + currentUrl);

分解 URL 各部分

console.log("协议: " + window.location.protocol);
console.log("主机: " + window.location.host);
console.log("路径: " + window.location.pathname);
console.log("查询字符串: " + window.location.search);
console.log("锚点: " + window.location.hash);

动态修改页面 URL

// 修改当前页面的URL(会重定向页面)
window.location.href = "https://www.example.com/newpage.html";

CSS 扩展

虽然 CSS 不能直接获取 URL,但可以使用属性选择器基于 URL 应用样式:

/* 当链接指向当前页面时应用特殊样式 */
a[href=""] {
    color: red;
    font-weight: bold;
}

/* 基于URL中的锚点应用样式 */
section:target {
    background-color: yellow;
}

注意事项

  1. window.location.hrefdocument.URL 在大多数情况下返回相同值

  2. 修改 window.location.href 会导致页面重定向

  3. 这些属性在浏览器环境中可用,Node.js 等服务器端环境不可用