2013-07-16 22 views
8

我已經使頁面的主體高達200%,因此它適合在屏幕上兩次。使用JavaScript我讓它在滾動時保持滾動到頂部或底部。爲此,我需要在任何瀏覽器或屏幕大小上找出頁面的最低滾動點,以便在它到達時停止。找到頁面的最大滾動位置

請勿使用JQuery。
謝謝。

我的代碼:(它仍然被放在一起,以便需要一些工作)

function getScrollXY() { 
    var x = 0, y = 0; 
    if(typeof(window.pageYOffset) == 'number') { 
     // Netscape 
     x = window.pageXOffset; 
     y = window.pageYOffset; 
    } else if(document.body && (document.body.scrollLeft || document.body.scrollTop)) { 
     // DOM 
     x = document.body.scrollLeft; 
     y = document.body.scrollTop; 
    } else if(document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) { 
     // IE6 standards compliant mode 
     x = document.documentElement.scrollLeft; 
     y = document.documentElement.scrollTop; 
    } 
    return [x, y]; 
} 

function scrollup() { 
    if (xy[1] > 0) { 
     window.scrollBy(0,-100); 
     setTimeout(scrollup,200); 
    } else { 
     null; 
    } 
} 

function scrolldown() { 
    if (xy[1] <) { 
     window.scrollBy(0,100); 
     setTimeout(scrolldown,200); 
    } else { 
     null; 
    } 
} 

function dothescroll() { 
    var xy = getScrollXY(); 
    var y = xy[1]; 
    setTimeout(function(){ 
     if (xy[1] > y) { 
      scrollup(); 
     } else { 
      scrolldown(); 
     } 
    },200); 
} 

回答

18

這是跨瀏覽器兼容的版本:

var limit = Math.max(document.body.scrollHeight, document.body.offsetHeight, 
        document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight); 
+3

如果你然後減去由window.innerHeight,這是最大滾動位置的限制。0 –

+7

不是真的: var limit = Math.max (document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight) - window.innerHeight; – Jordan

6
var limit = document.body.offsetHeight - window.innerHeight; 
// document.body.offsetHeight = computed height of the <body> 
// window.innerHeight = available vertical space in the window 

比較xy[1] < limit

注:您可能需要增加保證金的數值和/或身體的填充。您也可以嘗試使用clientHeight而不是offsetHeight

+0

這是完美的:) x –

+0

不完美的抱歉,它不是跨瀏覽器兼容。我會在下面發佈它: –

+0

@尼爾 - 我沒有完全得到你最後的評論。請分享您用這個發現的問題。 – vsync

1

window.scrollTo(0,document.body.scrollHeight);

這將工作..

+0

請詳細說明此線路無法工作的原因並提出解決方法 – tutuDajuju

0

雖然這不是任何規範的一部分,你可以嘗試window.scrollMaxY

返回文檔可以垂直滾動的最大像素數。 https://developer.mozilla.org/docs/Web/API/Window/scrollMaxY


回退;如果不可用:

var scrollMaxY = window.scrollMaxY || (document.documentElement.scrollHeight - document.documentElement.clientHeight) 

注意,documentElement並不總是滾動元件(某些瀏覽器使用body代替)。解決方案是新的scrollingElement屬性,其中返回對滾動文檔的元素的引用。這是規定的,但仍然是一個工作草案。

相關問題