2016-01-19 47 views
0

這裏的範圍到底是我到目前爲止的代碼:當頁面滾動與120像素的它添加的jQuery/CSS - 添加固定元件上滾動,並刪除它時,元素

$(window).scroll(function() {  
    var scroll = $(window).scrollTop(); 

    if (scroll >= 120) { 
     $("#FixedBox").addClass("fixed"); 
    } else { 
     $("#FixedBox").removeClass("fixed"); 
    } 
}); 

有了這個代碼類別fixed添加到ID爲FixedBox的元素。

我想要什麼?

ID爲FixedBox的元素包含在ID爲Content的元素中。因此,當頁面滾動120像素時,我的腳本將fixed類別附加到FixedBox,這使得它得到修復。

FixedBox到達Content的末尾時,我該如何刪除fixed類?

下面是示例圖像:

enter image description here

我怎麼能做到這一點?

我希望你能幫助我!

+0

'$ ('#footer')。offset()'可能對此有幫助。找出頁腳開始的位置,窗口的高度以及固定框的高度,並計算'.scroll(...)'需要移除固定類的點數 – user3154108

+0

您可以將它形成爲這個問題的答案嗎? –

回答

0

您可以在jQuery API Docs中找到$('#content').offset()$('#footer').offset()以上的位置來查找內容的結尾。

當您計算元素和位置的高度時,您可以計算出需要移除固定類的固定類的最高閾值。請記住,當您返回到DOM流時,您還需要更改固定框的非固定位置,否則它將跳回到起始位置。

+0

我有一個問題:當固定類被移除時,元素會在某個地方停下來,還是會在收到固定類之前返回到它的第一個位置? –

0

`

var maxScroll = 120 + document.getElementById('#content').offsetHeight; 
 
if (scroll >= 120 && scroll <= maxScroll) { 
 
    $("#FixedBox").addClass("fixed"); 
 
} else { 
 
    $("#FixedBox").removeClass("fixed"); 
 
}

你只需要得到#content高度。

1

您可以創建一個函數,檢查滾動高度是否在內容的開始和結束之間,並相應地添加該類。如果您有多個內容塊,這甚至會起作用。

Live Demo(第三內容框是目標)

HTML

<div class="content"> 
    <div class="box"> 
    </div> 
</div> 

<div class="content" id="target"> 
    <div class="box"> 
    </div> 
</div> 

CSS

.content{ 
    width: 100%; 
    height: 400px; 
    background: red; 
    margin-bottom: 20px; 
    position: relative; 
} 

.fixed{ 
    width: 100px; 
    height: 100px; 
    position: fixed; 
    right: 10px; 
    top: 10px; 
    background: blue; 
    display: block; 
} 

jQuery的

var content = $('#target'); 
$(window).scroll(function() {  
    var scroll = $(window).scrollTop(); 
    var offset = content.offset(); 
    var height = content.height(); 
    if (offset.top <= scroll && scroll <= offset.top + height) { 
     $('.box', content).addClass("fixed"); 
    } else { 
     $('.box', content).removeClass('fixed'); 
    } 
});