2014-10-28 63 views
0

我有一長頁的內容,我想爲它創建一個工具欄,並將其懸停在頁面頂部。我已經設法完成了,但是我也需要做到這一點,一旦頁面上的頁腳div到達,那麼懸停的div將會淡出。以下是我迄今所做的:使用jquery滾動div,當到達頁腳時淡出

function sticky_relocate() { 

var window_top = jQuery(this).scrollTop(); 
var div_top = jQuery('#anchor').offset().top; 
var footer_top = jQuery('.footer-container').offset().top; 
//var length = jQuery('.main').height() - jQuery('#fixed-toolbar').height() + jQuery('.main').offset().top; 
//var height = jQuery('.main').height() + 'px'; 

if (window_top > div_top) { 
    jQuery('#fixed-toolbar').addClass('fixed'); 
} else if (window_top > footer_top) { 
    jQuery('#fixed-toolbar').removeClass('fixed'); 
} else { 
    jQuery('#fixed-toolbar').removeClass('fixed'); 
} 

//console.log(height); 
} 

jQuery(function() { 
jQuery(window).scroll(sticky_relocate); 
sticky_relocate(); 
}); 

這裏是我的html的粗略表示:

<div id="anchor"> 
    <div id="fixed-toolbar"> 
     This is a test 
    </div> 
</div> 

<div> 
    Static text blocks<br> 
</div> 

<div class="footer-container"> 
    This is the footer<br> 
</div> 

你能告訴我,我要去哪裏錯了嗎?我找不到如何在「footer-container」div到達時淡出滾動div。

我已經創建了一個的jsfiddle,這裏的鏈接:http://jsfiddle.net/5bcaz88p/1/

回答

1

在這裏,你是一個工作示例http://jsfiddle.net/5bcaz88p/2/

你別的/如果條件是假的,基本上是因爲你有他們永遠不會在第二去如果(如果(window_top> footer_top)),因爲window_top將總是滿足第一個條件(它將比div_top大),並且它將永遠不會到達第二個條件。第二個if應該作爲單獨條件:)

function sticky_relocate() { 

    var window_top = jQuery(this).scrollTop(); 
    var div_top = jQuery('#anchor').offset().top; 
    var footer_top = jQuery('.footer-container').offset().top; 

    if (window_top > div_top) { 
     jQuery('#fixed-toolbar').addClass('fixed'); 
    } else { 
     jQuery('#fixed-toolbar').removeClass('fixed'); 
    } 

    if (window_top > footer_top) { 
     jQuery('#fixed-toolbar').removeClass('fixed'); 
    } 

} 

jQuery(function() { 
    jQuery(window).scroll(sticky_relocate); 
    sticky_relocate(); 
}); 
+0

啊!當然!簡直不敢相信它是如此簡單。感謝Bojan。 – 2014-10-28 20:18:02

+0

很高興我可以幫助:)你可以接受答案,這樣的問題可以被關閉:) – 2014-10-28 20:19:32