使用waypoints监听滚动事件scrollspy

本来使用bootstrap自带的 affix 好像很方便的样子,但是我的导航条已经自定义好了,同时发现affix列表长度如果超过当前页面的话会被截断,所以就放弃affix了ORZ……

先祭出神器 waypoints !

使用waypoint特别需要注意的是,如果在一个div中使用waypoint是需要指定context的……(简直不敢说自己纠结了大半天 waypoints not working)

import jquery.waypoints.min.js,以下代码实现了滚动内容时导航栏自动切换到对应的 a 标签:

$('.contentMark').each(function() {
          $(this).waypoint(function(direction) {
              $('.aList a').removeClass("active");
              var tmpHref = '#' + this.element.id;
              $('#aList a').each(function() {
                    if ($(this).attr("href") == tmpHref) {
                        if (direction == 'down') {//如果向下滚动经过一个mark,则置当前mark对应的导航a置为激活
                            $(this).addClass('active');
                        } else if (direction == 'up') {//如果向上滚动经过一个mark,则置当前mark的上一个mark对应的导航a置为激活
                            $(this).prev().addClass('active');
                        }
                        return false;//break
                    }
                });
            }, {
              context: document.getElementById('content')
            });
        });

你可能感兴趣的:(使用waypoints监听滚动事件scrollspy)