2017-08-07 65 views
1

在我的情況下,標題在滾動時變得固定,但只有當我們向上滾動一點時纔可見,而當我們向下滾動時隱藏,這就是所有工作正常。如何檢測滾動值是否超過窗口高度?

要求:標題只應該可見,如果我向上滾動,滾動至少應該是窗口高度。例如,如果我的窗口高度是700像素,那麼只有當我將頁面向上滾動700px時,頁眉才應該可見,並且當我向下滾動頁面時立即隱藏。

在此先感謝。

+0

可能的複製[如何確定jQuery窗口的高度和滾動位置?](https://stackoverflow.com/quest離子/ 303767 /如何做我確定高度和滾動位置的窗口在jquery) – Teemu

+0

對不起,但在這裏我不尋找窗口的滾動位置, 的要求是:什麼時候我從任何位置向上滾動(並且滾動值應該高於窗口高度),那麼標題應該出現。 –

回答

0

使用此代碼:

演示:http://output.jsbin.com/ricohevexu

<script> 
$(window).scroll(function (e) { 
    var height = $(window).scrollTop(); 
    var winheight = $(window).height(); 
    if(height > winheight) { 
    // Do something 
    console.log("Scroll height is more that window height!"); 
    } 
}); 
</script> 
+0

Chandra,根據你的代碼,它計算從頂部的值,我想要什麼,假設我在頁面中間,如果我滾動(高達700px這是我的窗口高度),那麼頭應該是可見的。 –

1

試試這個:相對於身體

$(window).scroll(function(){ 
    var containerHeight = $('.section-1').height(); 
    var windowHeight = ($(window).scrollTop()); 
    if(windowHeight > containerHeight){ 
    $(".header").removeClass('header-solid'); 
    } else { 
    $('.header').addClass('header-solid'); 
    } 
}); 
+1

我認爲這應該是正確的做法。 –

0

1.get位置相對於父元素的位置偏移得到,如果父節點不是body,繼續。

2.get滾動位置 這取決於如何滾動。如果本地滾動,通過element.scroll獲取滾動值是可以的。如果使用變換,必須得到改變x或y值

3.body位置 - 滾動位置

例如:

export const getBodyLeft = (e:HtmlElement) => { 
let offsetLeft = el.offsetLeft; 
const offsetParent = el.offsetParent; 
if (el.offsetParent && el.offsetParent.nodeName.toUpperCase() !== 'BODY'){ 
    offsetLeft += getBodyLeft(<HTMLElement>el.offsetParent); 
} 
return offsetLeft 

}

export const getViewTop = (el: HTMLElement, view: HTMLElement) => { 
const bodyTop = getBodyTop(el); 
const scrollView = view || document.body; 
let scrollTop = scrollView.scrollTop; 
let transformTop = 0; 
const transform = getComputedStyle(<Element>view).transform; 
if (transform) { 
    const matrix = transform.match(/((-|\d|\.)+)/g) || []; 
    const len = matrix.length; 
    if (matrix && len > 0) { 
     transformTop = Math.abs(Number(matrix[matrix.length - 1])); 
    } 
} 
scrollTop += transformTop; 
return bodyTop - scrollTop; 

}

相關問題