javascript - Scrollspy 效果停止工作

标签 javascript jquery html navigation scroll

scrollspy 效果正常,但突然停止工作。我的意思是当 href 链接像这样 href="#id"时,在滚动单页站点时识别菜单的事件元素。但是当 href 像“/home#id”一样给出时它停止工作。我想像这样使用它。由于该站点使用通用导航。
这是我的代码:

 / Cache selectors
var lastId,
    topMenu = $("#timenav"),
    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");
   }                   
});

谁能帮我解决这个问题

http://www.drkeenly.com/

这是一个 fiddle

http://jsfiddle.net/aGjTV/

任何帮助都会很棒。提前致谢 !

最佳答案

var cur = scrollItems!=null?scrollItems.map(...):null;

在这行之后 cur 要么是 something 要么是 null。 如果它为 null,则您不能像数组一样对其进行索引,或者就此而言,使用 cur.length 获取其长度。

您没有指定错误,但我敢打赌它说的是“TypeError:cur is null”。 解决方案取决于您实际希望代码执行的操作,但我建议将函数的其余部分包装在

if (cur) {
...
}

关于javascript - Scrollspy 效果停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21526583/

相关文章:

javascript - 使用 jQuery 转换一个 div 来显示另一个

javascript - AngularJS - 防止未经身份验证的用户访问给定的路由

ajax - 加载动态 "chosen"选择元素

javascript - 如何检测 JavaScript 中的数组相等性?

javascript - 内容保留在粘性标题下

javascript - jQuery 在页面上设置单选按钮

javascript - 图形分辨率会使网页变慢吗?

javascript - 使用 Angular 指令使用 element.bind(event, function) 调整触发器上文本区域的大小

javascript - 带有谷歌地图和天气图像的网页只能在 IE 中使用,不能在 Chrome 中使用?

javascript - 继承时原型(prototype)方法中的“this”未按预期解析