[英]On page scroll add active class to matching <a href>hash in fixed menu
這個人已經花了我一些時間來弄清楚,所以我呼吁有人來改善我的生活。
如果您的菜單鏈接僅包含#hashlocation,那么這段流行的代碼非常有用-當您瀏覽頁面的那部分時,它將使用活動類更新菜單項。
// Cache selectors
var topMenu = $("#top-menu"),
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 : "";
// Set/remove active class
menuItems
.parent().removeClass("active")
.end().filter("[href=#"+id+"]").parent().addClass("active");
});
對我來說 , 問題是,如果我的菜單包含非哈希標簽的其他頁面,則顯然不起作用,尤其是那些帶有哈希標簽的頁面,它們之前都帶有完整的URL 。
我需要調整此代碼,以便它不會引發“語法錯誤,無法識別的表達式”,並且還接受菜單可能包含指向其他位置的其他鏈接這一事實。
這是一個小提琴http://jsfiddle.net/stevenmunro/ytbhrz1g/2/
如果您要從“ Foo”中刪除哈希之前的完整URL,它將起作用。
我努力了
menuItems = topMenu.find('a[href*=#]'),
以及在scrollItems = menuItems.map中
var item = $($(this).attr("href").split("#"));
item = $("#" + item[1]);
參考文獻
感謝您的幫助。
感謝James Hay使我走上正確的道路。 該建議與我已經嘗試過的建議非常相似,但是現在它是單線的,並且效果很好。
我也改變了;
menuItems = topMenu.find("a"),
至
menuItems = topMenu.find('a[href*=#]'),
並且改變了;
menuItems
.parent().removeClass("active")
.end().filter("[href=#"+id+"]").parent().addClass("active");
至
menuItems
.parent().removeClass("active")
.end().filter("[href$=" + id + "]").parent().addClass("active");
只要菜單中的項目以及它們在頁面中的順序過高,就可以使用。 如果菜單項被加擾,則不會按預期更改。 也許這也是我們可以解決的其他問題,但問題已得到解答,非常感謝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.