天天看點

手工寫的一段滾動條監聽事件

$(document).ready(function(){
    var flag =0;//設定參數
    $('.g-submit li').on('click',function(){
        flag = 1;//點選是改變參數的值
        $(this).addClass('g-nav-active').siblings().removeClass('g-nav-active');
        var _this = $(this).index();
        var _gScrTop = $(eval('g_scroll'+_this)).offset().top +'px';
        /*var _ngScrTop = parseInt(_gScrTop);*/
        $("html,body").animate({scrollTop: _gScrTop},500,function(){
            flag = 0;//function回調函數改回參數值
        });
    })
    $(window).on('scroll',function(){
        var _gNavHeight = $('.g-banner').height()+110;
        var _documentScroll = $(document).scrollTop();
        var $gNav = $('.g-nav');
        var _gheight = $('.g-nav').height();
        if(_documentScroll >= _gNavHeight){
            $gNav.css({'position':'fixed','top':'0'})
        }
        if(_documentScroll < _gNavHeight){
            $gNav.css({'position':'absolute','top':'470px'})
        }
        if(flag == 0){//判斷參數值
            $('.g-submit li').each(function(){//循環li的length
                var _this = ($(this).index());//存儲每個li的索引值
                var _gScrollTop = $(eval('g_scroll'+_this)).offset().top-_gheight;
                if(_documentScroll >= _gScrollTop){
                    $('.g-submit li').eq(_this).addClass('g-nav-active').siblings().removeClass('g-nav-active');
                }
            });
        }
    })
})