159 words
1 minutes
Frontend Development Learning Notes 4
The core idea behind a fixed navigation bar that automatically highlights sections based on the page’s scroll position is to determine the relationship between the current scroll value and the position of the corresponding content on the page. The JavaScript code is as follows (using the jQuery library):
$(document).ready(function () {
$(window).scroll(function () {
var top = $(window).scrollTop();
var menu = $("#menu");
var items = $("#content").find(".item");
// When the scrollbar scrolls, get the relevant values.
var currentId = "";
// Make the navigation menu automatically highlight the current section when the scrollbar scrolls.
items.each(function () {
var This = $(this);
var itemTop = This.offset().top;
if (top > itemTop - 200) {
currentId = This.attr("id");
} else {
return false;
}
})
// Set the 'current' class for the corresponding section's link and remove it from other links.
var currentLink = menu.find(".current");
if (currentId && currentId != "#"+currentLink.attr("href")) {
currentLink.removeClass("current");
menu.find("[href=#" + currentId + "]").addClass("current");
}
})
})
This article was published on December 31, 2014 and last updated on December 31, 2014, 3932 days ago. The content may be outdated.
Frontend Development Learning Notes 4
https://blog.kisnows.com/en-US/2014/12/31/learning-note-4/