滚动删除其他页面中的课程的活动菜单

时间:2018-05-03 11:55:48

标签: jquery wordpress

我正在通过WordPress做一个网站。由于post,我在this之后滚动实现了活动菜单。

我让它成功了,但因为我使用链接代替了' href' (" http://wordpress/#aboutus"而不是#aboutus)现在有一些问题。导航栏上的某些项目具有外部页面,滚动不会为其添加课程。

CODE:

菜单项:

var lastId,
  topMenu = $("#mainnav"),
  topMenuHeight = topMenu.outerHeight()+15,
  // All list items
  menuItems = topMenu.find("a"),
  // Anchors corresponding to menu items
  scrollItems = menuItems.map(function(){

    ////////// temp
    var temp = $(this).attr("href"); 
    console.log('temp', temp ); // Output example: "http://localhost/wordpress/#aboutus"

    ////////// ID
    var ID
    if (temp.indexOf('#') > -1) { // If link = "http://localhost/wordpress/#aboutus"
      ID = temp.split('#').pop(); // Output: "aboutus"       
    } else { 
      ID = temp.split('/').pop(); // if doesn't have "#"
    }
    console.log('ID', ID );

    ///////// item
    var item = temp.split('/').pop();

    if(!ID){
      console.log('ID undefined');
      var item = $('body');
    } else {
      var item = $('#'+ID);
    }
    console.log('item', item );

    if (item.length) { return item; }
  });

滚动操作:

// Bind to Control
$(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 : "";
console.log("cur", cur);
console.log("id", id);
if (lastId !== id) {
  lastId = id;
  // Set/remove active class
  menuItems
    .parent().removeClass("current-menu-item")
    .end().filter("[href='http://localhost/wordpress/#"+id+"']").parent().addClass("current-menu-item");
   }
 });

如何删除那些没有&#34;#&#34;或者将类添加到其他页面而不是通过滚动删除?

1 个答案:

答案 0 :(得分:0)

好,我已更改

menuItems = topMenu.find('a[href*="#"]')

因此它将获取所有在href中包含#的锚点(a)。