scroll2078

navigation bar behavior based on scroll bar

目前为 2024-03-30 提交的版本。查看 最新版本

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.greasyfork.org/scripts/491240/1351511/scroll2078.js

        document.addEventListener('DOMContentLoaded', function () {
            const header = document.querySelector('.header');
            let lastScrollTop = 0;
            header.style.top = '-18px'; // Start with the header -18px from the top

            function handleScroll() {
                let scrollTop = window.pageYOffset || document.documentElement.scrollTop;

                // Calculate the difference in scroll position
                let delta = scrollTop - lastScrollTop;

                // If scrolling down or at the top of the page, do nothing
                if (delta > 0 || scrollTop === 0) {
                    header.style.top = '-18px';
                } else {
                    // Scrolling up - Calculate new top value
                    let newTop = parseInt(header.style.top, 10) + Math.abs(delta);

                    // Ensure the header doesn't move past the top boundary (0)
                    if (newTop > 0) newTop = 0;

                    header.style.top = `${newTop}px`;
                }

                // Update the last scroll position
                lastScrollTop = scrollTop;
            }

            window.addEventListener('scroll', handleScroll);
        });