2016-09-22 13 views
0

スクロールダウン時にnavの<a>要素の色を変更したいとします。スクロール時にnavタグの色を変更します

ここに私のレポhttps://github.com/sebalaini/Twelfth_Project_Treehouse.com と、ここで私が間違って何を、私は私のプロジェクトのためにこのコードを変更するが、それは動作しません、元のjqueryのコードにhttps://codyhouse.co/gem/vertical-fixed-navigation/

を取る場所の例?ここで

var contentSections = $('.section'); 
var navigationItems = $('.nav a'); 

updateNavigation(); 
$(window).on('scroll', function(){ 
    updateNavigation(); 
}); 

function updateNavigation() { 
    contentSections.each(function(){ 
     $this = $(this); 
     var activeSection = $('.nav a[href="#'+$this.attr("class")+'"]'); 
     if (($this.offset().top - $(window).height()/2 < $(window).scrollTop()) && ($this.offset().top + $this.height() - $(window).height()/2 > $(window).scrollTop())) { 
      navigationItems.eq(activeSection).addClass('selected'); 
     }else { 
      navigationItems.eq(activeSection).removeClass('selected'); 
     } 
    }); 
} 

答えて

0

はcodepenです:http://codepen.io/esten/pen/GjAxRX

は、いくつかの問題があります。 activeSectionセレクタは、必要なセクション識別子だけでなく、その要素のすべてのクラス名を返します。私はセレクターをクラスではなく.attr('id')に変更しました(私はポートフォリオセクションにIDを追加しなければなりませんでした。これに対応するためにポートフォリオヘッダーのIDを変更しました)。 activeSectionがあなたのアンカータグの要素を選択しているので

var contentSections = $('.section'); 
var navigationItems = $('.nav a'); 

updateNavigation(); 
$(window).on('scroll', function() { 
    updateNavigation(); 
}); 

function updateNavigation() { 

    contentSections.each(function() { 
    //console.log($(this)); 
    $this = $(this); 
    var activeSection = $('.nav a[href="#' + $this.attr("id") + '"]'); 

    if (($this.offset().top - $(window).height()/2 < $(window).scrollTop()) && ($this.offset().top + $this.height($(window).height()/2 >  $(window).scrollTop())) { 
     activeSection.addClass('selected'); 
    } else { 
     activeSection.removeClass('selected'); 
    } 
    }); 
} 

はまた、あなただけのその要素に直接クラスを追加する必要があります。

はこれのnav要素に適用selectedクラスを取得する必要があり、あなたはあなたのCSSのセレクタと、より具体的にする必要があります。このことができます

.nav a.selected { 
    color: blue 
} 

希望を!

+0

ありがとう、それはほぼ完璧です、家と連絡先だけがうまくいきません、私はこのコードについて考えています: if(($ this.offset().- $(window).height )/ 2 <$(window).scrollTop())&&($ this.offset()。top + $ this.height($(window).height()/ 2> $(window).scrollTop())) { 家と連絡先のウィンドウの高さを設定するにはどうすればいいですか? 私はrepoの更新を行いました;) – Sebastiano

+0

私はcodepenにいくつかのコメントを追加しました。それをもう一度チェックしてください。基本的に、コードは、要素がウィンドウの中央に当たるときを探しています。その "if"文をどのようにしたいのか調整したいでしょう。 明日もう一度見ていきます。 – Esten

+0

また、それがあなたを助けた場合は答えを受け入れてください:) – Esten

関連する問題