2012-06-18 25 views
1

同樣的方式,我用它來檢測時用戶scolled關閉整個頁面:如何檢索#div(包括溢出部分)的實際高度

$(window).scroll(function(){ 
    var diff = $(window).scrollTop() + $(window).height() - $(document).height(); 
    if ($(window).scrollTop() == $(document).height() - $(window).height() || (diff < 5 && diff > -5)){ 
      console.log('yay!'); 
    } 
}); 

我想做一個對話框中的一樣,

我想是這樣的:

$('#dialog').dialog(); 
$('#dialog').scroll(function(){ 
    var scroll = $('#dialog').scrollTop(); 
    var height = $('#dialog ul').outerHeight(true); 
    if(scroll == height){ 
     $('#dialog').css('background','#999'); 
    }else{ 
     console.log('scrolltop is '+scroll+' and height is: '+height); 
    } 
}) 

DEMO:

http://jsfiddle.net/AgFXz/

我想的問題是,我不是檢索整個#dialog大小,但可見(CSS定義的屬性)的大小..

我怎麼能知道當用戶滾動,直到對話框的滾動結束?

謝謝!

+0

請不要告訴我,我必須做它計算元素... –

+0

似乎是一樣的http://stackoverflow.com/questions/2522579/how-do-i-get-the-real-height溢出隱藏或溢出滾動分區 – Smileek

回答

1

使用$('#dialog ul')[0].scrollHeight獲取元素的滾動高度,然後減去實際高度$('#dialog ul').outerHeight(true);以知道用戶何時滾動到底部。

var height = $('#dialog ul')[0].scrollHeight - $('#dialog ul').outerHeight(true); 

DEMO

這是控制檯日誌中說,(我點擊了下來,每次箭頭)

scrolltop is 40 and height is: 250 
scrolltop is 80 and height is: 250 
scrolltop is 120 and height is: 250 
scrolltop is 160 and height is: 250 
scrolltop is 200 and height is: 250 
scrolltop is 240 and height is: 250 

最後,雙方scrollheight是250。這不在日誌中顯示,但如果你手動檢查,你會看到。

$('#dialog').scrollTop(); 
250 
+0

該演示無法正常工作,檢測高度= 0.因此,當用戶再次滾動到頂部時顏色發生變化 –

+0

這就是我所遇到的情況:滾動,無變化。只要滾動條碰到底部,顏色就會變爲#999。這不是你想要的嗎? – sachleen

+0

你在日誌中看到的高度不是0嗎?肯定是正確的鏈接?謝謝(這是我想要的,但它不會在演示中發生) –

0

大家都注意到了,你應該使用scrollHeight
但在您的演示另一個問題:

#dialog ul{ 
    height:150px; 
} 

當然$('#dialog ul').outerHeight(true)$('#dialog ul').innerHeight()和,甚至$('#dialog ul')[0].scrollHeight將等於150

您需要檢查溢出的元素的scrollHeight屬性,所以使用$('#dialog')[0].scrollHeight