基于IntersectionObserver实现H2进视口时横向滚动对应Scrollable Div锚点
实现锚点自动滚动到可见区域的修改方案
你只需要在IntersectionObserver的回调函数中,在高亮对应锚点的同时,调用锚点元素的scrollIntoView()方法,就能让它自动滚动到横向容器的可见区域。
修改核心逻辑
在检测到H2进入视口时:
- 获取当前H2的ID
- 匹配对应的锚点元素
- 调用锚点的
scrollIntoView(),配置横向滚动的参数
完整修改后的代码
HTML(无需修改)
<div class="horizontal-scroll"> <a href="#section1" class="anchor">Section 1</a> <a href="#section2" class="anchor">Section 2</a> <a href="#section3" class="anchor">Section 3</a> </div> <div class="content"> <h2 id="section1">Section 1</h2> <p>大量内容...</p> <h2 id="section2">Section 2</h2> <p>大量内容...</p> <h2 id="section3">Section 3</h2> <p>大量内容...</p> </div>
CSS(无需修改)
.horizontal-scroll { overflow-x: auto; white-space: nowrap; padding: 10px; background: #f5f5f5; } .anchor { display: inline-block; padding: 8px 16px; margin: 0 8px; text-decoration: none; color: #333; border-radius: 4px; } .anchor.active { background: #2196f3; color: white; } .content { max-width: 800px; margin: 20px auto; } h2 { margin-top: 800px; /* 用于测试滚动效果 */ }
JavaScript(修改部分已标注)
const anchors = document.querySelectorAll('.anchor'); const headings = document.querySelectorAll('h2'); // 初始化IntersectionObserver const observer = new IntersectionObserver((entries) => { entries.forEach(entry => { const headingId = entry.target.id; const correspondingAnchor = document.querySelector(`.anchor[href="#${headingId}"]`); if (entry.isIntersecting) { // 移除所有锚点的高亮类 anchors.forEach(anchor => anchor.classList.remove('active')); // 高亮当前锚点 correspondingAnchor.classList.add('active'); // --- 新增:让锚点滚动到横向容器的可见区域 --- correspondingAnchor.scrollIntoView({ behavior: 'smooth', // 平滑滚动,可改为'auto'实现立即跳转 block: 'nearest', // 垂直方向保持原有位置 inline: 'center' // 横向居中显示锚点,可选'start'靠左/'nearest'自动适配 }); // --- 新增结束 --- } }); }, { threshold: 0.5 }); // 监听所有H2标题 headings.forEach(heading => observer.observe(heading));
自定义适配说明
如果你的锚点和H2不是通过href与id关联,而是用自定义属性(比如data-target),只需要把匹配锚点的选择器改成document.querySelector(.anchor[data-target="${headingId}"])即可。
内容的提问来源于stack exchange,提问作者Marius123
相关产品推荐
相关产品推荐

