访问带锚点的页面链接时自动打开对应闭合的details下拉面板
用原生JavaScript即可实现该需求,无需修改现有HTML结构,示例代码如下:
document.addEventListener('DOMContentLoaded', function() { // 获取URL中的锚点部分 const targetHash = window.location.hash; if (!targetHash) return; // 提取目标元素ID const targetId = targetHash.slice(1); const targetElement = document.getElementById(targetId); if (!targetElement) return; // 向上遍历所有父节点,展开所有包裹目标元素的details面板 let currentNode = targetElement; while (currentNode.parentElement) { currentNode = currentNode.parentElement; if (currentNode.tagName.toLowerCase() === 'details') { currentNode.setAttribute('open', 'open'); } } // 手动滚动到目标位置,确保定位准确 targetElement.scrollIntoView(); // 需要平滑滚动可以替换为下行代码 // targetElement.scrollIntoView({ behavior: 'smooth' }); });
以上逻辑兼容多层嵌套的details面板,就算锚点元素处于多层折叠面板内部,也会逐层展开所有上级面板。
如果需要支持页面内点击锚点跳转时也自动展开对应面板,可以额外添加hash变化监听逻辑:
window.addEventListener('hashchange', function() { const targetHash = window.location.hash; if (!targetHash) return; const targetId = targetHash.slice(1); const targetElement = document.getElementById(targetId); if (!targetElement) return; let currentNode = targetElement; while (currentNode.parentElement) { currentNode = currentNode.parentElement; if (currentNode.tagName.toLowerCase() === 'details') { currentNode.setAttribute('open', 'open'); } } targetElement.scrollIntoView(); });
内容的提问来源于stack exchange,提问作者Chr1zz
相关产品推荐
相关产品推荐

