【问题标题】:Sticky navigation & hover on divs粘性导航和悬停在 div 上
【发布时间】:2013-10-22 10:21:31
【问题描述】:

我是 jQuery 和 JS 的新手,所以请善待:)

我的页面顶部有一个粘性导航栏,它链接到下面的各个内容部分(页面位置)。 我想要达到的效果是让相关部分在用户开始阅读时自动突出显示(即使他们手动滚动到它而不是点击链接)。

这是我正在谈论的一个示例(*请注意导航栏在您滚动与之关联的页面时 div 是如何变化的):http://www.domo.com/

我现在正在使用 jQuery 粘性插件让菜单保持在顶部,但不知道如何进行悬停。

【问题讨论】:

  • 请澄清您的具体问题或添加其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。
  • 我见过更糟糕的书面问题——至少提供了一个例子。

标签: javascript jquery html css


【解决方案1】:
【解决方案2】:

问题基本上分为两部分:

1.我的每个部分在页面上的什么位置?

为了突出显示每个部分的导航元素,您首先需要知道每个部分的位置。

我建议使用.section 之类的类来定义您的部分,并使用name 属性来确定哪个是哪个,因此您的标记看起来像这样:

<html>
  <head>...etc.</head>
  <body>

    <ul>
      <li class="nav" id="nav_one">1</li>
      <li class="nav" id="nav_two">2</li>
    </ul>

    <div class="section" name="one"> Section one</div>

    <div class="section" name="two"> Section two</div>

  </body>
</html>

JavaScript 查找每个部分的位置:

//define a sections object
var sections = {}

//find all sections on the page, then for each:
$('.section').each(function(){
  //add a property to the object with a key corresponding to the name
  //and a value corresponding to the offset from the top of the page.
  sections[$(this).attr('name')] = $(this).offset().top;
});

2。用户在页面的哪个位置?

谜题的第二部分是找出哪些部分在视图中。这会随着用户滚动而改变,因此正如您所料,您需要使用 jQuery 的 scroll() 事件处理程序:

//the function passed as an argument will be called every time the user scrolls.
$(document).scroll(function(){
  //get the new position
  var newPos = $(this).scrollTop();

  //configurable variable to decide how close a new section needs to be to the
  //top of the page before it's considered the active one.
  var OFFSET = 100;

  //look at all the sections you have, and work out which one should be
  //considered active.
  for(name in sections){
    if(sections[name] > newPos && sections[name] < newPos + OFFSET){
      //the section with name = name is within OFFSET of the top

      //remove "active" styling from the previously active nav elements
      $('.nav').removeClass('active');

      //make the nav element with an id of nav_sectionname active.
      $('#nav_' + name).addClass('active'); 
    }
  }
});

Codepen example here

【讨论】:

  • 为什么不简单地使用 HTML5 部分? .nav 也不是必需的。将菜单包裹在 nav 中并相应地选择菜单元素。
  • 是的,您可以这样做以获得更多语义含义。不过,问题更多的是关于 JavaScript 的实现而不是 html。我认为我的回答足以说明如何解决这部分问题。
  • 确实如此。我只是指出需要改进的小点。
猜你喜欢
  • 1970-01-01
  • 2020-07-23
  • 1970-01-01
  • 2020-02-05
  • 2012-03-31
  • 1970-01-01
  • 2012-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多