前言

所谓直梯导航就是类似各种技术文档中右侧menu和文档的跳转和高亮。现在用vue2实现一个建议的导航控件。

以下给出一种思路,使用场景是滚动列表中的子项仅有一个可完整展示在视口内。

  1. 滚动⇒控件高亮

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    // 给滚动容器绑定监听,不用了记得删除一下监听
    this.$refs.listWrap.addEventListener("scroll", this.handleScroll);

    handleScroll() {
    const listWrap = this.$refs.listWrap;
    // 获取滚动容器所有子项
    const items = listWrap.querySelectorAll(".item");
    let foundIndex = 0;
    // 遍历子项
    items.forEach((item, index) => {
    // 获取子项的domRect对象
    const rect = item.getBoundingClientRect();
    // 判定其距离视口的top和bottom是否在当前视口内部
    if (rect.top >= 0 && rect.bottom <= window.innerHeight) {
    foundIndex = index;
    }
    });
    // 获取到子项
    this.activeIndex = foundIndex;
    // 接下来可以对直梯控件做一些focus/active处理
    // ...
    },
  2. 点击控件高亮⇒滚动到对应位置

    1
    2
    3
    4
     this.$refs[yourRefName][0].$el.scrollIntoView({
    // behavior: "smooth", // 参数可以自行去mdn做采购
    block: "center",
    });

done!