绑定菜单项与滚动时的Jquery错误

时间:2015-04-05 23:28:58

标签: javascript jquery html menu navigation

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

这是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/

我发现代码不处理绝对url:

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>
每件事情都顺利进行。但有了它,发生了那些错误,并且没有发生菜单滚动效果。

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

1 个答案:

答案 0 :(得分:0)

经过两天的搜索并试图了解问题所在,我就解决了。(请参阅此页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 /);这是不正确的。

相关问题