javascript - 单页网站上复杂的事件状态导航

标签 javascript jquery navigation

HTML:

<div class="logo-ribbon">
    <a href="#top"></a>
</div>

<nav id="nav">

    <ul>
        <li class="what">
            <a href="#what">what </a>
        </li>
        <li class="how">
            <a href="#how">how </a>
        </li>

        <li class="projects">
            <a href="#projects">projects</a>
        </li>
        <li class="faq">
            <a href="#faq">faq</a>
        </li>
        <li class="contact">
            <a href="#contact">contact</a>
        </li>
    </ul>

</nav>

JS:

$('nav li a').click(function(e) {
        e.preventDefault();
        $('a').removeClass('active-state-navigation');
        $(this).addClass('active-state-navigation');

        $('logo-ribbon a').click(function(){
        $('nav li').removeClass('active-state-navigation');
    });
});

我需要实现以下目标:

  • 单击菜单项后的经典事件状态..我已经通过 js 的第一行实现了这一点

  • 我希望在页面滚动时也能触发事件状态。这样,如果我滚动到 #contact 部分,事件状态就会更改为“联系人”菜单项

  • 我还需要,如果我点击“.logo-ribbon a”,“事件状态导航”将被删除在导航中的任何位置。

最佳答案

你是说滚动 spy 吗?检查这里http://jsfiddle.net/mekwall/up4nu/

// Cache selectors
var lastId,
    topMenu = $("#top-menu"),
    topMenuHeight = topMenu.outerHeight()+15,
    // 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 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 (lastId !== id) {
       lastId = id;
       // Set/remove active class
       menuItems
         .parent().removeClass("active")
         .end().filter("[href=#"+id+"]").parent().addClass("active");
   }                   
});

关于javascript - 单页网站上复杂的事件状态导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17145609/

相关文章:

javascript - 如何提交焦点表单

javascript - Google Analytics 跟踪代码已缩小

javascript - 使用 javascript 应用视差效果时图像在晃动

javascript - 如何在选择下拉列表更改时获取属性值

javascript - 为多个页面上的导航栏创建可重用的 html

javascript - React 无法识别 DOM 元素上的 `initialValue` 属性

jquery - 如何在 jquery 的 .html() 中执行 jquery/javascript 代码

jquery - 有人能告诉我为什么我的 overflow-x 会影响我的菜单边框吗?

navigation - React Native 中的室内平面图

firebase - Flutter:即使在屏幕之间导航后也会保存页面的状态