web-dev-qa-db-ja.com

設定Bootstrapスクロール時のナビゲーションバーの透明度

bootstrapコードを上書きするためにcustom.cssと呼ばれるセカンダリフィルを使用します。サイトの訪問者が一番上にいない場合にのみアクティブになるコードを作成する方法を知りたいです。ページの。

これまでは、ブートストラップによって提供されるデフォルトのコードを使用して、透明なナビゲーションバーを作成しました。私がしなければならない唯一のことは、実行するように設定することです:background-color: #color訪問者が下にスクロールしているとき。

例: https://www.lyft.com/

ページの上部にいるときは、ナビゲーションバーは透明ですが、下にスクロールすると不透明になります。

11
Hiperkie

この効果を実現するには、次のコードが必要です。(bootstrapサポートされている言語であるため、jQueryを使用します)。


jQuery:

/**
 * Listen to scroll to change header opacity class
 */
function checkScroll(){
    var startY = $('.navbar').height() * 2; //The point where the navbar changes in px

    if($(window).scrollTop() > startY){
        $('.navbar').addClass("scrolled");
    }else{
        $('.navbar').removeClass("scrolled");
    }
}

if($('.navbar').length > 0){
    $(window).on("scroll load resize", function(){
        checkScroll();
    });
}

ScrollSpyを使用してこれを行うこともできます。


そしてあなたのCSS(例):

/* Add the below transitions to allow a smooth color change similar to lyft */
.navbar {
    -webkit-transition: all 0.6s ease-out;
    -moz-transition: all 0.6s ease-out;
    -o-transition: all 0.6s ease-out;
    -ms-transition: all 0.6s ease-out;
    transition: all 0.6s ease-out;
}

.navbar.scrolled {
    background: rgb(68, 68, 68); /* IE */
    background: rgba(0, 0, 0, 0.78); /* NON-IE */
}
33
David Passmore
$(document).ready(function() {
    $(window).scroll(function() {
       if($(this).scrollTop() > height) { 
           $('.navbar').addClass('scrolled');
       } else {
           $('.navbar').removeClass('scrolled');
       }
    });
});
0
saad