实现横向滑动带锚点的粘性导航

导航内容超出屏幕,向左滑动显示更多,点击导航,定位到页面相应的模块,导航元素未达到该设定距离时随页面滚动,在距离页面指定距离的时候吸附置顶(距离默 top 认为 0)


scrollIntoView()方法会滚动元素的父容器,使被调用scrollIntoView()的元素对用户可见

  • nav某项只显示一半的情况下(比如div5),选中后滚动导航使其全部显示给用户

block 可选参数
定义垂直方向的对齐, "start", "center", "end", 或 "nearest"之一。默认为 "start"

页面需要锚点的模块设置 className 通过 index 与导航对应

// 组件
export default ({ navList = [] }) => {
  const [activeNav, setActiveNav] = useState(1);
  const tabChange = (params: React.SetStateAction<number>) => {
    setActiveNav(params);
    const temp = document.getElementsByClassName('scrollDiv')[params];
    temp.scrollIntoView({ behavior: 'smooth', block: 'center' });
  };
  return (
    <div className="container">
      <div className="nav_box_fixed">
        <div className="nav_wrapper_fixed">
          {navList.map((item, index) => {
            return (
              <div
                key={index}
                className={`block ${
                  activeNav === index ? 'tab_block_selected' : ''
                }`}
                onClick={(target) => {
                  // nav某项只显示一半的情况下,选中后滚动导航使其全部显示给用户
                  if (target.pageX > 316) {
                    document
                      .getElementsByClassName('nav_wrapper_fixed')[0]
                      .scroll(target.pageX + 40, 0);
                  }
                  tabChange(index);
                }}
              >
                <span>{item}</span>
                {activeNav === index ? <div className="line"></div> : ''}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};
// 样式
.container {
  position: sticky; //  导航吸顶
  top: 88px; //  距离顶部 88px 时 fixed
  z-index: 3;
  width: 100%;
  padding-left: 16px;
  padding-right: 16px;
  background: #fff;
  box-shadow: 0px 4px 8px rgba(228, 235, 241, 0.5);
  border-radius: 2px;
}

.nav_wrapper_fixed {
  display: flex;
  white-space: nowrap; // 重要
  overflow-x: scroll;  // 重要
  overflow-y: hidden; // 重要
  touch-action: pan-x; // 移动端滑动
  &::-webkit-scrollbar { // 隐藏滚动条
        display: none;
        width: 0;
        height: 0;
   }
  .block {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    margin-right: 40px;
  }
  .line {
    width: 50px;
    height: 4px;
    background: #1492ff;
    border-radius: 2px;
  }
  .tab_block_selected {
    color: #1492ff;
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容