2014-04-02 128 views
2

我一直在尋找這個幾天,但仍然沒有快樂!滾動div直到頁腳頂部

我想有一個固定位置的div滾動,直到它到達頁腳的頂部。

這裏是什麼,我至今小提琴:http://jsfiddle.net/danieljoseph/uk4mC/

我使用這個jQuery代碼,但這種使用像素確定DIV停止時。我想用在頁腳的頂部,停止點:

$(document).scroll(function() { 
var scrollVal = $(document).scrollTop(); 
$('#floating-container').css('top',scrollVal+'px'); 
if (scrollVal < 50) { 
    $('#floating-container').css('top','50px'); 
} 
if (scrollVal > 2347) { 
    $('#floating-container').css('top','2347px');  
} 
}); 

的問題是,我使用的是CMS和客戶端將添加文本的頁面,以便第二個值將根據改變什麼他們補充道。

我希望我已經清楚了!如果您需要更多詳細信息,請告訴我。

感謝,

回答

4

如果您的的底部邊緣您必須檢查滾動事件低於頁腳。如果是,請將div放在footer的位置減去div的高度。

$(function(){ 
    var container = $('#floating-container'); 
    var minTop = $('header').outerHeight(); 
    var maxTop = $('footer').offset().top - container.outerHeight(); 

    $(document).scroll(function() { 
     var scrollVal = $(document).scrollTop(); 

     container.css('top', scrollVal); 

     if (scrollVal < minTop) { 
      container.css('top', minTop); 
     } 

     if (container.offset().top > maxTop) { 
      container.css('top', maxTop);  
     } 
    }); 
}); 

Fiddle

而且,腳本的上述短得多的變種:

$(function(){ 
    var container = $('#floating-container'); 
    var minTop = $('header').outerHeight(); 
    var maxTop = $('footer').offset().top - container.outerHeight(); 

    $(document).scroll(function() { 
     container.css('top', Math.min(Math.max(minTop, $(document).scrollTop()), maxTop)); 
    }); 
}); 

Short version fiddle

+0

小提琴看起來不錯,但我認爲你可以緩存浮動容器jquery對象 – Huangism

+0

更新 - >添加了一個更短的實現。 – Cristy

+0

如果我想讓浮動容器始終位於屏幕底部而不是頂部? (但在頁腳處停止) –

0

剛纔看了頁腳位置上方時加載頁面:

http://jsfiddle.net/uk4mC/1/

var footerTop = $('#text-block').position().top; 

,然後使用它作爲一個觸發器:

if (scrollVal < footerTop) { }