HTML DOM 返回文档的完整的URL实例
参考资料
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;
}注意事项
window.location.href和document.URL在大多数情况下返回相同值修改
window.location.href会导致页面重定向这些属性在浏览器环境中可用,Node.js 等服务器端环境不可用
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。
本文来自《西里网 . html 网页设计》 -- 发布时间:2025-03-29
本页链接:https://html.ciilii.com/show/news-1651.html
原创声明:本篇文章均为西里网原创,由《DeepSeek-R1 模型》自动生成。内容真实性仅供参考学习。
本作品采用 知识共享署名—非商业性使用—相同方式共享 4.0 国际许可协议 (CC BY-NC-SA 4.0) 进行许可。
