【问题标题】:How can I get these menu items to highlight depending on the current page section?如何根据当前页面部分突出显示这些菜单项?
【发布时间】:2015-05-06 02:46:45
【问题描述】:

我相信答案在于 jQuery,我已经尝试了几种解决方案。

我的问题的根源是我正在修改这个网站,而我不是设计它的人。它是用 wordpress 制作的,但主题是高度定制的。这是一个包含多个部分的单页站点,顶部的菜单带有这些部分的锚链接。 我已经能够在单击时更改突出显示类,但是当相应部分在屏幕上可见时,我也需要更改它。我知道这应该很简单,但是这个网站的复杂性让我感到厌烦。

这是菜单的 HTML:(其中一些类指向 style.css 文件的很大一部分。我不确定是否值得一提,所以请告诉我)

<div class="ddsmoothmenu"><ul id="menu-home-2" class="menu">
<li class="menu-item"><a class="link" href="#home">Home</a></li>
<li class="menu-item"><a class="link" href="#our-story">Our Story</a></li>
<li class="menu-item"><a class="link" href="#services">Services</a></li>
<li class="menu-item"><a class="link" href="#tools">Tools of the Trade</a></li>
<li class="menu-item"><a class="link" href="#faqs">FAQs</a></li>
<li id="menu-item-310" class="menu-item"><a href="/category/blog/">Blog</a></li>
<li class="menu-item"><a class="link" href="#contact">Contact</a></li>
</ul></div>

我在同一个文件中用于活动 CSS 更改的样式:

<style>
a, a:visited { color:black }
a.link.active { color:blue; }
</style>

这是改变颜色的点击事件的脚本:

<script>
$(function() {
   $('a.link').click(function() {
       $('a.link').removeClass('active');
       $(this).addClass('active');
   });
});
</script>

我知道很多事情做得很糟糕......所以请原谅。 我想如果我能检测到当前可见的部分 ID,并激活关联菜单项的 CSS 类,那将是发薪日。救命!

【问题讨论】:

  • 突出显示,您的意思是您希望当前单击的菜单项为蓝色?或者您正在寻找添加背景颜色?
  • 我一直把它染成蓝色。背景可能同样有用。要点是能够根据当前可见的锚点更改菜单项的 CSS。
  • 如果你想访问被点击链接的封装 li,你可以使用 $(this).parent() 或 $(this).closest('li') 或 $( this).closest('.menu-item').
  • 您是否要在用户滚动页面并传递菜单中列出的锚标记时突出显示菜单?
  • 是的@Hassaan,正是

标签: jquery css menu anchor highlight


【解决方案1】:

我认为this jsFiddle 项目应该可以帮助您回答您的问题。该链接来自 this 之前的 SO 答案。

您必须将滚动事件绑定到窗口或某个容器。

上一个 SO 答案的快速示例:

// Cache selectors
var topMenu = $(".ddsmoothmenu"),
topMenuHeight = topMenu.outerHeight(),

// All list items
menuItems = topMenu.find("a"),

// Anchors corresponding to menu items
scrollItems = menuItems.map(function(){
  var item = $($(this).attr("href"));
  if (item.length) { return item; }
});

// 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 : "";
   // Set/remove active class
   menuItems
     .parent().removeClass("active")
     .end().filter("[href=#"+id+"]").parent().addClass("active");
});​

【讨论】:

  • 我把它添加到了网站上。我觉得它应该真的可以工作,但可能应用于菜单项的 div 和 ul 的类有干扰。
  • 我会尝试一下,看看能不能得到一些结果。
猜你喜欢
  • 2011-10-27
  • 2016-02-25
  • 1970-01-01
  • 2014-09-06
  • 1970-01-01
  • 1970-01-01
  • 2012-09-17
  • 1970-01-01
相关资源
最近更新 更多