提问者:小点点

滚动定位链接上的活动导航


我已经想了好几个小时了。我目前有一个固定的导航我的锚网站。我想要菜单链接背景颜色改变时滚动通过每个部分。像这样:https://codepen.io/dbilanoski/pen/labpzg。当我滚动每个部分时,我只看到悬停背景颜色,而不是活动状态颜色。如果你有什么提示或建议,请指教。

谢谢!

null

var navLink = $(".nav-link"),
  topMenuHeight = navLink.outerHeight() + 15,
  //All list items
  menuItems = navLink.find("a"),
  //Anchors corresponding to menu items
  scrollItems = menuItems.map(function() {
    var item = $($(this).attr("href"));
    if (item.length) {
      return item;
    }
  });
// Bind click handler to menu items
// so we can get a fancy scroll animation
menuItems.click(function(e) {
  var href = $(this).attr("href")
  offsetTop = href === "#" ? 0 : $(href).offset().top - topMenuHeight + 1;
  $('html, body').stop().animate({
    scrollTop: offsetTop
  }, 300);
  e.preventDefault();
});
// Bind to scroll
$(window).scroll(function() {
  // Get container scroll position
  var fromTop = $(this).scrollTop() + topMenuHeight;

  // Get id of current scroll item
  var cur = scrollItems.map(function() {
    if ($(this).offset().top < fromTop)
      return this;
  });
  // Get the id of the current element
  cur = cur[cur.length - 1];
  var id = cur && cur.length ? cur[0].id : "";

  if (navLink !== id) {
    navLink = id;
    // Set/remove active class
    menuItems
      .parent().removeClass("active")
      .end().filter("[href='#" + id + "']").parent().addClass("active");
  }
});
a {
  color: inherit;
  text-decoration: none;
}

a:hover {
  color: #fa448c;
  text-decoration: underline;
}

a:active {
  background-color: #fa448c;
  color: #fff;
}

li {
  list-style-type: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="menu">
  <ul class="nav-list">
    <li class="nav-item">
      <a href="#home" class="nav-link">Home</a>
    </li>
    <li class="nav-item">
      <a href="#products" class="nav-link">Products</a>
    </li>
    <li class="nav-item">
      <a href="#featured" class="nav-link">Featured</a>
    </li>
    <li class="nav-item">
      <a href="#best-sellers" class="nav-link">Best Sellers</a>
    </li>
    <li class="nav-item">
      <a href="#contact" class="nav-link">Contact</a>
    </li>
  </ul>
</div>

null


共1个答案

匿名用户

你发送的代码页的诀窍是所有部分都有相同的高度。然而,有一种更灵活的方法。使用此解决方案,您可以检查每个部分是否显示在屏幕上,如果显示了,则在navlist中突出显示它的按钮。