2010-09-03 65 views
1

我使用jQuery.scrollTop()來獲取滾動條的位置。我正在嘗試創建一個動畫,該動畫將向用戶指示他們在內容列表中的位置。這是一個名稱列表,當用戶滾動Q字符時,我希望有一個大的「Q」在列表上滾動。jQuery.scrollTop()在滾動條移動時不會更新

似乎只有在停止移動後,scrollTop()纔會提供準確的信息滾動條。當我實際移動滾動條時,它不反映位置。

domElement.scrollTop是否可以跨瀏覽器使用?爲什麼滾動條移動時jquery.scrollTop不更新?

+0

快速測試顯示,在Firefox中,domElem.scrollTop實際上做了更新,而我滾動。好奇的jhttp.scrollTop()沒有。我想知道它在其他瀏覽器上的表現如何。 – morgancodes 2010-09-03 20:19:37

+0

好吧,我當時很蠢。抱歉的人。那個jsfiddle的東西很漂亮。下一次,我會先在那裏重新創建我的錯誤。 – morgancodes 2010-09-03 21:45:08

回答

1

這似乎爲我工作:http://jsfiddle.net/nPqez/

這是用來讓代碼它的工作:

HTML

<div id="test"> 
    <div>test</div> 
    <div>test</div> 
    <div>test</div> 
    <div>test</div> 
    <div>test</div> 
    <div>test</div> 
    <div>test</div> 
    <div>test</div> 
    <div>test</div> 
    <div>test</div> 
    <div>test</div> 
    <div>test</div> 
    <div>test</div> 
    <div>test</div> 
    <div>test</div> 
    <div>test</div> 
    <div>test</div> 
    <div>test</div> 
    <div>test</div> 
    <div>test</div> 
</div> 

<div id="message"> 
Current scroll position: 0 
</div>​ 

JS:

$('#test').scroll(function() { 
    $('#message').text("Current scroll position: " + $(this).scrollTop()); 
});​ 

CSS:

#test { 
    height:200px; 
    border:1px solid silver; 
    border-radius:5px; 
    overflow:scroll; 
    margin-top:20px; 
}​ 
+0

太棒了。我在做一些愚蠢的事情(只有在用戶暫停後更新我的滾動位置變量)。所以,呃,當然我沒有得到我所表達的行爲。 – morgancodes 2010-09-03 21:43:10

2

嘗試將scroll()事件附加到窗口並在此處進行測試。

$(window).scroll(function() { 
     //$(window).scrollTop() is accurate and updated while scrolling 
}); 

下面是這個工作演示:http://jsfiddle.net/LydQE/

+0

謝謝安德!這是我的代碼中的一個錯誤,而不是jquery,因爲你已經很好地展示了它。 – morgancodes 2010-09-03 21:43:55