导航栏监听页面滚动跟随 简单封装

slide('.wedding-title', '.expo-list', 'change','.nav'); //导航条  参数:导航栏父级, 被监听元素 , 导航改变样式,导航栏
function slide(navfather, tClass, activeClass,nav) {
    var $navfather = $(navfather),
        $nav = $(nav);
    $navfather.css({
        "position": 'relative'
    });
    var $navfatherOffset = $navfather.offset().top,
        $navfatherH = $navfather.height();
    var arrayH = [];
    $(tClass).each(function(i, list) {
        arrayH.push($(this).offset().top - $navfatherH * 3 / 2)
    });
    $nav.find('li').click(function(e) {
        e.preventDefault();
        var index = $(this).index();
        $('body,html').stop().animate({
            scrollTop: arrayH[index] + 10
        }, 200)

    });
     $(window).scroll(function(){
            if ($(window).scrollTop()>=$navfather.offset().top){
                $nav.css({'position':'fixed','zIndex':'7'});
            }else{
                $nav.css({'position':'absolute'});
            }
        arrayH.forEach(function(h, i) {
            
            if ($(window).scrollTop() >= h) {
                $navfather.find('li').eq(i).addClass(activeClass).siblings('li').removeClass(activeClass);
            }
        })
    })
}

猜你喜欢

转载自www.cnblogs.com/wxyblog/p/12021573.html