一旦用户滚动离开锚点部分,如何 "re-activate" a link?

How to "re-activate" a link once the user scrolls away from an anchor section?

我正在使用 Vue.js 2.3.3 和 vue-router 2.5.3。我创建了一个 Navbar 组件,其中包含指向着陆页上特定部分的书签(或 links),如下所示:

<router-link to="/#our-services" class="nav-item item is-tab">
    Our Services <!-- Jumps to #our-services on the home page -->
</router-link>

我按以下方式定义了我的路由器:

export default new VueRouter({
    routes, // routes are defined in a var above...
    mode: 'history',
    scrollBehavior(to, from, savedPosition) {
        if (to.hash) {
            return { selector: to.hash }
        } else {
            return { x: 0, y: 0 }
        }
    },
    linkActiveClass: 'is-active'
})

现在,这似乎行得通;如果我在导航栏中单击 "Our Services" link,它会跳转到 #our-services然而:

  1. 如果我滚动离开 #our-services div 元素,然后再次单击 "Our Services" link,它不会让我回到 div;单击 link 不会产生任何内容;
  2. 此外,router-link<a> 元素保留了 is-active class,即使您滚动离开了该部分;最好跟踪您在页面上的位置并适当调整 link 上的 is-active class。

关于如何解决这两个问题有什么建议吗?在第二种情况下我应该听滚动事件吗?谢谢!

无论你的滚动对象是什么(可能window),你都应该添加一个事件监听器来处理滚动事件:

window.addEventListener('scroll', scrollHandler, false);

你的scrollhandler函数应该检查当前window位置是否有散列,如果有,检查关联元素是否超出范围,如果有,清除散列.

我不能在片段中使用真实位置哈希或 window,但这正是您想要做的。

let hash = '#second';
const scrollingEl = document.querySelector('.scrollingArea');

function handleScrollEvent() {
  if (hash) {
    const winY = scrollingEl.scrollTop;
    const hashElY = document.querySelector(hash).getBoundingClientRect().top;
    
    if (hashElY < 0 || hashElY > winY + scrollingEl.height) {
      hash = '';
    }
    console.log(winY, hashElY);
  }
}

scrollingEl.addEventListener('scroll', handleScrollEvent, false);
.scrollingArea {
  height: 400px;
  overflow-y: scroll;
}

.scrollingArea>div {
  height: 250px;
}
<div class="scrollingArea">
  <div id="first">First</div>
  <div id="second">Second</div>
  <div id="third">Third</div>
  <div id="fourth">Fourth</div>
</div>