2016-12-25 68 views
0

我試圖做一個簡單的滾動與jQuery滾動事件,但它失敗。這裏是我的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有「內容」ID。如果我更改了「內容」ID的JavaScript代碼,它就可以工作。這真的很奇怪。

如果你想看到它,請訪問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 
     } 
    }); 
    }); 
}); 

我希望這是你正在尋找的,或至少讓你開始的東西。