抹桥的博客
Language
Home
Archive
About
GitHub
Language
主题色
250
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");
            }
        })
    })
Frontend Development Learning Notes 4
https://blog.kisnows.com/en-US/2014/12/31/learning-note-4/
Author
Kisnows
Published at
2014-12-31