滚动时突出显示菜单不起作用

时间:2016-11-03 05:36:28

标签: javascript scroll

当相关元素进入视图时,我正在尝试在滚动时突出显示菜单链接。我看到this answer,我试图用纯JavaScript编写它。问题是,当我向下滚动时,菜单链接会随机获得活动的类。

我做错了什么,我该如何解决?

JSFiddle



window.addEventListener('scroll', selectLink)

var sections = {
  link1: document.getElementById('1'),
  link2: document.getElementById('2'),
  link3: document.getElementById('3'),
  link4: document.getElementById('4'),
};

function selectLink() {
  var prevTarget = document.querySelector('.active');
  var docHeight = document.documentElement.clientHeight;

  for (var sectionKey in sections) {
    if (!sections.hasOwnProperty(sectionKey)) continue;

    var sectionKeyRect = sections[sectionKey].getBoundingClientRect();

    if ((window.pageYOffset || doc.scrollTop) >= sectionKeyRect.top) {
      prevTarget.classList.remove('active');
      document.querySelector('#' + sectionKey).classList.add('active');
    }
  }
}

* {
  margin: 0;
  padding: 0;
}
#main {
  width: 75%;
  float: right;
}
#main div.target {
  background: #ccc;
  height: 400px;
}
#main div.target:nth-child(even) {
  background: #eee;
}
#nav {
  width: 25%;
  position: relative;
}
#nav nav {
  position: fixed;
  width: 25%;
}
#nav a {
  border-bottom: 1px solid #666;
  color: #333;
  display: block;
  padding: 10px;
  text-align: center;
  text-decoration: none;
}
#nav a:hover,
#nav a.active {
  background: #666;
  color: #fff;
}

<section id="main">
  <div class="target" id="1">TARGET 1</div>
  <div class="target" id="2">TARGET 2</div>
  <div class="target" id="3">TARGET 3</div>
  <div class="target" id="4">TARGET 4</div>
</section>
<aside id="nav">
  <nav>
    <a id="link1" class="active">First</a>
    <a id="link2">Second</a>
    <a id="link3">Third</a>
    <a id="link4">Fourth</a>
  </nav>
</aside>
&#13;
&#13;
&#13;

0 个答案:

没有答案