【问题标题】:Active Navigation On Scroll anchor links滚动锚链接上的活动导航
【发布时间】:2020-12-11 03:46:26
【问题描述】:

我已经尝试了好几个小时来解决这个问题。我目前有一个固定的导航用于我的锚网站。我希望在滚动浏览每个部分时更改菜单链接背景颜色。像这样:https://codepen.io/dbilanoski/pen/LabpzG。当我滚动浏览每个部分时,我只看到悬停背景颜色而不是活动状态颜色。如果您有任何提示或建议,请提出建议。

谢谢!

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>

【问题讨论】:

    标签: javascript html jquery css


    【解决方案1】:

    您发送的 codepen 的诀窍是所有部分都具有相同的高度。但是,有一种更灵活的方法可以做到这一点。使用this solution,您可以检查每个部分是否显示在屏幕上,如果是,则在导航列表中突出显示其按钮。

    【讨论】:

    • 谢谢!我通读了这篇文章,似乎应该使用 Intersection Observer API。但是有很多不同的答案,所以我不太确定是否应该使用 Intersection Observer API。
    猜你喜欢
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 2018-10-16
    相关资源
    最近更新 更多