2016-12-25 11 views
0

jQueryスクロールイベントで簡単なscrollspyを作成しようとしていますが、失敗します。ここに私のJavaScriptの一部は次のとおりです。jQueryスクロールイベントがセクションで動作しない

<script> 
$(document).ready(function(){ 
    $("#credit_card").scroll(function(){ 
    console.log('OK'); 
    }); 
}); 
</script> 

とHTML部分:

<section class="method first-of-group" id="credit_card"> 
... 
</section> 

ご想像のとおり、console.logは単なるテストのためです。このセクションはdivの下にあり、このdivには "content" idがあります。 JavaScriptコードを "content" idに変更すると、動作しています。本当に変だ。

ライブをご覧になりたい場合は、hereにアクセスしてください。

ありがとうございます。

+0

問題は、セクションのいずれかでスクロールしないことです。スクロールバーがないので、セクション自体ではなくドキュメント自体を下にスクロールします。 –

+0

あなたのセクションにこのCSSを追加すると、私の言いたいことが分かります... 'overflow-y:scroll; overflow-x:scroll; 身長:300px; ' –

+0

@GerritLuimstraありがとうございました。それを動作させるための提案はありますか? –

答えて

1

コメントを読み、実際に何を意味しているのかを理解した後、これがあなたが探している解決策です。

$(document).ready(function(){ 
    $("#content").scroll(function(){ 

    // when the user scrolls, we want to detect at what section they currently are. 
    // This can be calculated, by comparing the current window scrolltop to the position and height of the section elements. 
    var currentTopOffset = $(document).scrollTop(); 

    $('section').each(function(){ 
     var min = $(this).offset().top; 
     var max = $(this).offset().top + $(this).height(); 
     if(currentTopOffset > min && currentTopOffset < max){ 
      // current section 
      // do something here, like getting a value from an input type hidden with the section name 
     } 
    }); 
    }); 
}); 

私はこれがあなたが探しているもの、またはあなたが始めようとするものがほしいと思っています。