代码样例

"use strict";
(function($) {
    $.fn.navLight = function(option) {
        option = option || {};
        var nav = option.nav || "[data-widget=nav]";
        var content = option.content || "[data-widget=content]";
        var diffTop = option.diffTop || 200;
        var diffBottom = option.diffBottom || 500;
        var lightCls = option.lightCls || "curr";
        var preCallback = option.preCallback || null;
        var diffPreCb = preCallback ? option.diffPreCb : 400;
        var callback = option.callback;

        var $self = $(this);
        var $nav = $self.find(nav);
        var $content = $self.find(content);

        var contentPosi;

        // 记录每个分类的位置
        function collectPos() {
            var pos = $content.map(function(idx, elem) {
                var $cont = $(elem);
                var top = $cont.offset().top;
                // var height = $cont.height();
                return {
                    top: top - diffTop,
                    bottom: top + diffBottom,
                    jq: $cont
                };
            });
            contentPosi = pos;
        }
        collectPos();


        var $win = $(window);
        var $doc = $(document);

        var handler = function() {
            var dTop = $doc.scrollTop();
            highLight(dTop);
        };

        function highLight(docTop) {
            contentPosi.each(function(idx, posi) {
                if (preCallback) {
                    if (posi.top - diffPreCb < docTop && posi.bottom > docTop) {
                        preCallback($nav, $content, posi.jq);
                    }
                }

                if (posi.top < docTop && posi.bottom > docTop) {
                    $nav.removeClass(lightCls);
                    $nav.eq(idx).addClass(lightCls);
                    if (callback) {
                        callback($nav, $content, posi.jq);
                    }
                }
            });
        }

        function update() {
            collectPos();
            handler();
        }

        // 初始化的时候检查一次位置,防止通过锚点访问造成的显示错误。
        handler();
        // $win.scroll(handler);
        $win.scroll(update);

        // 对外挂载更新方法,方便其他地方更改DOM高度后更新。
        $.fn.navLight.update = update;
    };


})(window.$ || require("jquery"));