【发布时间】:2018-10-13 17:42:32
【问题描述】:
我正在通过 WordPress 做一个网站。由于this,我在post 之后在滚动上实现了活动菜单。
我让它工作了,但是因为我使用的是链接而不是 'href' 上的 id(“http://wordpress/#aboutus”而不是 #aboutus)现在有一些问题。导航栏上的某些项目有外部页面,滚动不会给它们添加类。
代码:
菜单项:
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");
}
});
如何删除那些没有“#”的页面或向其他页面添加类而不被滚动删除?
【问题讨论】: