bata's log

フロントエンド系のTipsとかメモ

スクロールすると表示されるナビゲーション

スクロール型のナビゲーションがあるサイトで、一定の位置までスクロールするとナビゲーションが固定で出てくるサイトがあります。

こういうの↓
http://gion-renge.jp/

これが結構よく使う演出なので使いまわせるように書いてみました。

function NavControl(el,position,height,time,easing){
    this.$el = $(el);
    this.position = position;
    this.height = height;
    this.time = time || 200;
    this.easing = easing || 'linear';
    this.$window = $(window);
    this.event();
}

NavControl.prototype = {

    event: function(){
        var that = this;
        this.$window.on('scroll', function(){
            var scrollTop = that.getScrollTop(this);
            that.decidePosition(scrollTop);
        });
    },

    getScrollTop: function(self){
        return $(self).scrollTop();
    },

    decidePosition: function(scrollTop){
        if( scrollTop > this.position ){
            this.animation(0);
        }else{
            this.animation(this.height);
        }
    },

    animation: function(n){
        this.$el.stop().animate({top: n}, this.time, this.easing);
    }
}

実行

$(function(){
    //init
    new NavControl('selector', 136, -50);
});

初期化して実行します。
第1引数にセレクター、第2引数にナビゲーションが表示されるスクロール位置、第3引数にナビゲーションのTOPの値(隠れている時のTOPの値)を設定して使用します。

第4引数はアニメーションのスピード、第5引数はイージングを設定しますが、設定無しでも動作します。