【问题标题】:Jquery error when binding menu item with scrolling将菜单项与滚动绑定时出现 Jquery 错误
【发布时间】:2015-04-05 23:28:57
【问题描述】:

我尝试将导航菜单与滚动绑定。效果:当我滚动窗口浏览器时,活动菜单项将突出显示。

这是html:

<ul class="navigation">
    <li><a href="#intro">HOME</a></li>
    <li><a href="#anchor1">Link 1</a></li>
    <li><a href="#anchor2">Link 2</a></li>
    <li><a href="#anchor3">Link 3</a></li>
    <li><a href="#anchor4">Link 4</a></li>
    <li><a href="#anchor5">Link 5</a></li>
    <li><a href="http://localhost/pages/blog/">BLOG</a></li>
</ul>

jquery 代码是:

$(window).load(function(){
// Cache selectors
var lastId,
    topMenu = $(".navigation"),
    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 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");
   }                   
});

此错误出现在 firbug 控制台上:

Error: Syntax error, unrecognized expression: http://localhost/pages/blog/

我发现代码没有处理绝对网址:

var item = $($(this).attr("href")); 

然后我将其替换为:

var item = $(this).attr('href').split('=');

现在这个错误已经显示:

    TypeError: $(...).offset(...) is undefined
if ($(this).offset().top < fromTop)

注意,当我删除 html 行时:

<li><a href="http://localhost/pages/blog/">BLOG</a></li>

一切顺利。但是有了它,这些错误发生了,菜单滚动效果没有发生。

你有什么线索,问题出在哪里?我该如何解决?

【问题讨论】:

  • 你能设置fiddle,和/或提供css和html的其余部分吗?
  • @nevermind 我用的是firebug。。我已经插入了相关的html,剩下的很长,包含很多部分,每个部分都有ID。关于css,它只是改变活动类的颜色。

标签: javascript jquery html menu navigation


【解决方案1】:

经过两天的搜索,试图了解问题出在哪里,我解决了。(请参考此页面as the resource of my solution

在jquery中替换这段代码:

scrollItems = menuItems.map(function(){
  var item = $($(this).attr("href"));
  if (item.length) { return item; }
});

使用此代码:

// Anchors corresponding to menu items
scrollItems = menuItems.map(function(){

  var indexItm = $(this).attr('href').indexOf('#');
  if (indexItm >= 0) {
    var str = $(this).attr('href').substring(indexItm);
    var item = $(str);
    if (item.length) { return item; }
    }
})
;

就是这样。

var item = $($(this).attr("href"));在代码中产生了问题,因为当您编写 href="#id" 时,它是 var item = $(#id);但是当你写 href="/blog/" 它变成 var item = $(/blog/);这是不正确的。

【讨论】:

    猜你喜欢
    • 2016-08-24
    • 2012-10-07
    • 1970-01-01
    • 2016-11-21
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多