You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何实现单个锚点链接滚动到页面两个不同区域?

实现侧边栏锚点与对应内容同时滚动到顶部

要实现点击侧边栏锚点时,锚点自身和对应内容区域元素同时滚动到顶部,只需在现有点击事件逻辑里新增对被点击侧边栏列表项的滚动处理即可,具体操作如下:

  1. 先给侧边栏容器添加滚动能力:
    给.aside类设置样式,确保内容超出时可滚动(高度值可根据你的布局调整):
.aside {
  max-height: calc(100vh - 8rem);
  overflow-y: auto;
}
  1. 修改锚点点击事件逻辑,同时处理内容区域和侧边栏的滚动:
const items = Array.from({ length: 15 }, (_, index) => `items from strapi ${index}`);
// ... 其他代码

<div className="flex gap-4 items-start mt-16 mx-16">
  <div className="aside">
    <ul>
      {items.map((item, index) => (
        <li className="h-16" key={index}>
          <a
            onClick={(e) => {
              e.preventDefault();
              // 处理内容区域目标元素滚动
              const targetElement = document.getElementById(`${index}`);
              if (targetElement) {
                targetElement.scrollIntoView({ behavior: 'smooth' });
              }
              // 处理当前侧边栏列表项滚动到顶部
              const currentLi = e.currentTarget.parentElement;
              currentLi.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }} 
            href={`#${index}`}
          >
            {item}
          </a>
        </li>
      ))}
    </ul>
  </div>
  <div className='flex flex-col'>
    {items.map((item, index) => (
      <div id={`${index}`} className='flex pt-16'>
        {`${index}`} {loaderData?.overview}
      </div>
    ))}
  </div>
</div>

关键细节:

  • e.currentTarget.parentElement用来获取当前被点击<a>对应的父元素<li>
  • scrollIntoView的block: 'start'参数确保列表项滚动到侧边栏容器的顶部位置(默认值也是start,显式声明更清晰)
  • 必须给.aside设置固定高度和overflow-y: auto,否则侧边栏没有滚动区域,scrollIntoView不会生效

内容的提问来源于stack exchange,提问作者BigChungus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 07:02:41