2011-07-15 39 views
6

下面是我用來在用戶滾動時修復邊欄的代碼。截至目前,它與我的頁腳重疊。我怎樣才能讓它在某個點停下來,或者當它碰到頁腳時?如何使#footer固定浮動元素停止?

<script type="text/javascript"> 
    $(document).ready(function() { 
    if ($('.pageheaderwrap').length) { 
     $(window).scroll(function() { 
      if ($(this).scrollTop() > 362) { 
       $(".sidebar-left").css({ 
        "position": "fixed", 
        "top": 0 
       }); 
      } else { 
       $(".sidebar-left").css({ 
        "position": "absolute", 
        "top": "255px" 
       }); 
      } 
     }); 
    } else { 
     $(window).scroll(function() { 
      if ($(this).scrollTop() > 230) { 
       $(".sidebar-left").css({ 
        "position": "fixed", 
        "top": 0 
       }); 
      } else { 
       $(".sidebar-left").css({ 
        "position": "absolute", 
        "top": "125px" 
       }); 
      } 
     }); 
    } 
}); 
</script> 
+0

@Cyber​​nate:正要自己修復縮進。 :-) – GregL

+0

您可以計算出兩個元素(頁腳和側邊欄)之間的距離,當該距離<= 0時,您可以停止向下移動側欄。看看這篇文章:http://stackoverflow.com/questions/225563/get-relative-position-between-2-dom-elements-using-javascript。 –

回答

1

爲什麼不能消除所有的JavaScript與CSS做到這一點:

.sidebar-left { 
    position: fixed; 
    bottom: 20px; /* height of your footer */ 
} 
+0

我想象他希望它堅持到底部,直到它碰到頁腳,然後粘到頁腳的頂部。 – AlienWebguy

+0

啊,在這種情況下,當他到達頁腳時,他需要設置底部:頁腳高度 – Adam

+1

是的,我想要實現的一個完美例子是在Yelp上的右側地圖:http:// www。 yelp.com/search?find_desc=food&ns=1&find_loc=Santa+Rosa%2C+CA –

5

下面是一些可能爲你工作:

http://jsfiddle.net/y3qV5/7/

的jQuery插件,做這將設置元素固定頁面頂部的任何頁邊距。有了可選的限制,它將會解除該元素並使其繼續向上滾動頁面,使其遠離頁腳。您可以將限制設置爲頁腳的頂部,再加上目標元素的高度。

下面是此方案的代碼使用(以上小提琴):

$(document).ready(function() { 
    $('#cart').scrollToFixed({ 
     marginTop: 10, 
     limit: $('#footer').offset().top 
    }); 
}); 

這裏是鏈接到插件及其源:

https://github.com/bigspotteddog/ScrollToFixed

相關問題