
本文介绍如何在用户通过外部 URL(如 https://example.com/#section1)访问页面时,自动为目标锚点元素(如 <div id="section1">)添加 active 类,实现视觉高亮,弥补原生 :active 伪类仅作用于点击瞬间的局限。
本文介绍如何在用户通过外部 url(如 https://example.com/#section1)访问页面时,自动为目标锚点元素(如 `
当用户从站外(例如搜索引擎结果页、其他网站或书签)点击一个带锚点的链接(如 https://yoursite.com/page.html#features)进入页面时,浏览器会自动滚动到对应 id 元素,但不会触发 :active 伪类——因为 :active 仅在鼠标按下/触摸期间临时生效,且无法通过 URL 状态持久化。
要实现“访问即高亮”的效果,需借助 JavaScript 在页面加载时解析 URL 的 hash 部分,并手动为目标元素添加自定义类(如 .active),再通过 CSS 控制其样式。以下为推荐实现方案:
✅ 推荐实现(原生 JS,无需 jQuery)
现代项目建议使用原生 JavaScript 替代 jQuery,更轻量、兼容性好(支持 IE9+):
document.addEventListener('DOMContentLoaded', function() {
const hash = window.location.hash;
if (hash) {
const targetId = hash.substring(1); // 去掉 '#' 号
const element = document.getElementById(targetId);
if (element) {
element.classList.add('active');
// 可选:确保元素在视口内(尤其当页面有固定头部时)
element.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
}
});? CSS 样式示例
配合上述 JS,定义 .active 类以实现视觉反馈:
/* 示例:为锚点区域添加背景高亮和边框 */
.active {
background-color: #f0f8ff;
border-left: 4px solid #4285f4;
padding-left: 12px;
transition: all 0.2s ease;
}⚠️ 注意事项:
- ID 唯一性:确保 window.location.hash 解析出的 ID 在页面中真实存在且唯一,否则 getElementById() 返回 null;
- 时机安全:使用 DOMContentLoaded 而非 load,确保 DOM 就绪但不必等待图片等资源;
- SPA 兼容性:若使用 React/Vue 等框架,应在路由钩子(如 useEffect 或 mounted)中监听 location.hash 变化,而非仅依赖初始加载;
- 无障碍友好:可额外添加 aria-current="true" 属性提升可访问性:
element.setAttribute('aria-current', 'true');
✅ 进阶:监听 hash 变化(支持单页内导航)
若页面含内部锚点跳转(如导航菜单点击 #about),可补充监听 hashchange 事件,实现动态更新:
window.addEventListener('hashchange', function() {
// 移除之前所有 .active 元素
document.querySelectorAll('.active').forEach(el => el.classList.remove('active'));
// 为新 hash 目标添加 active
const hash = window.location.hash;
if (hash) {
const target = document.getElementById(hash.substring(1));
if (target) target.classList.add('active');
}
});通过以上方式,即可优雅地将“外部锚点访问”转化为可样式化的 DOM 状态,兼顾功能完整性与用户体验一致性。










