(function($) {
    $.fn.anchorFollow = function(options) {
        var settings = $.extend({
            offset: 0, // 默认偏移量为 0
            debounceDelay: 100 // 默认防抖延迟时间为 100 毫秒
        }, options);
        return this.each(function() {
            var nav = $(this);
            var scrolling = false;
            function scrollToSection(target) {
                $(‘html, body’).animate({
                    scrollTop: target.offset().top
                }, 500);
            }
            function highlightNav(target) {
                // 触发自定义事件
                nav.trigger(‘show’, {
                    hash: target,
                    dest: target.attr(‘id’)
                });
            }
            function handleScroll() {
                if (!scrolling) {
                    scrolling = true;
                    setTimeout(function() {
                        var scrollPosition = $(window).scrollTop();
                        nav.find(‘a’).each(function() {
                            var href = $(this).attr(‘href’);
                            var target = $(href);
                            if (target.length) {
                                var topOffset = target.offset().top;
                                if (scrollPosition >= topOffset – settings.offset) {
                                    highlightNav($(this));
                                }
                            }
                        });
                        scrolling = false;
                    }, settings.debounceDelay);
                }
            }
            // 初始调用
            handleScroll();
            // 监听滚动事件
            $(window).scroll(function() {
                handleScroll();
            });
            // 点击导航链接滚动到相应位置
            nav.find(‘a’).click(function(e) {
                e.preventDefault();
                var href = $(this).attr(‘href’);
                var target = $(href);
                if (target.length) {
                    scrollToSection(target);
                    highlightNav($(this));
                }
            });
        });
    };
})(jQuery);
实战:
下拉滑动页面,导航栏目可以跟随响应
var $nav = $(“.panel-tab”);
 if ($nav.size()>0) {
                $nav.anchorFollow({
                    offset:200
                });
                $nav.on(“show”, function(t, e) {
                    $nav.find(“a”).removeClass(“active”),
                    e.hash.addClass(“active”)
                })
                $nav.fixtop({
                    fixed:function(p){
                        p.addClass(‘fixed’);
                    },
                    unfixed:function(p){
                        p.removeClass(‘fixed’);
                    }
                });
}
注意:导航滑动过程中固定头部是由fixtop插件完成的

作者 admin

百度广告效果展示