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

导航内容超出屏幕,向左滑动显示更多,点击导航,定位到页面相应的模块,导航元素未达到该设定距离时随页面滚动,在距离页面指定距离的时候吸附置顶(距离默 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) => {
    setActiveNav(params);
    const temp = document.getElementsByClassName('scrollDiv')[params];
    temp.scrollIntoView({ behavior: 'smooth', block: 'center' });
  };
  return (
    
{navList.map((item, index) => { return (
{ // nav某项只显示一半的情况下,选中后滚动导航使其全部显示给用户 if (target.pageX > 316) { document .getElementsByClassName('nav_wrapper_fixed')[0] .scroll(target.pageX + 40, 0); } tabChange(index); }} > {item} {activeNav === index ?
: ''}
); })}
); }; // 样式 .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; // 重要 .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; } }

你可能感兴趣的:(实现横向滑动带锚点的粘性导航)