2014-10-16 81 views
0

我需要一個側邊欄,當用戶在頁面上滾動時,該邊欄會與固定位置保持一致。我遇到了很多解決方案,都非常笨重,複雜或太長。我需要它簡單而高效。我想它並使它:包含的粘性邊欄

var length = $('#container').height() - $('#stick').offset().top - parseFloat($('#stick').css('marginTop').replace(/auto/, 0)); 

$(window).scroll(function() { 

    var scroll = $(this).scrollTop(); 

    if (scroll < $('#container').offset().top) { 
     $('#stick').removeAttr("style"); 
    } 
    else if (scroll > length) { 
     $('#stick').css('position', 'absolute'); 
    } 
    else { 
     $('#stick').css({"position":"fixed", "top":"0", "right":"0"}); 
    } 
}); 

我的Remy Sharp screencast的幫助和waypointarts blog post

當#container的獲得在視口的末端#stick停止滾動做這個(「固定」的位置被移除),問題是它消失了,並沒有保持在該位置的絕對位置,這種行爲會干擾用戶。

如何讓#stick側欄完全定位在#container的底部而不是消失?你是否也認爲我的代碼可以完善?

我是業餘的,並開始使用jquery1個月現在,所以你會發現很多在這裏的錯誤...

謝謝。

+0

當足夠的瀏覽器支持它時,可以使用['position:sticky'](https://developer.mozilla.org/en-US/docs/Web/CSS/position#Sticky_positioning) – Oriol 2014-10-16 21:27:33

+0

哇太棒了。我不知道這個位置可用。感謝您指出它。目前還不是一個可靠的選項:http://caniuse.com/#search=sticky – 2014-10-16 22:32:15

回答

0

我設法做到了。我不知道爲什麼它會被貶低,但是我決定不直接將css屬性注入到html中,而是使用更適合css的方法,在實際的css文件中應用css,因爲html應該使用html語言。

所以這個想法我添加了CSS類與jQuery的行動和在CSS中我添加了這些類我想要的樣式,並且一切工作都很完美。也許這是一些重疊的CSS規則,之前做了一些錯誤......無論如何,它有更好的方法,它的格式更好。

所以,在html:

<body> 
    <header>The header</header> 
    <main id="container"> 
    <article id="content">Main content</article> 
    <section id="sticky">Sticking content</section> 
    </main> 
    <footer>The footer</footer> 
<body> 

jQuery的:

var $container = $('#container'); 
var $sticky = $('#sticky'); 
var length  = $container.height() + $container.offset().top - $sticky.height(); 

$(window).scroll(function() { 
    var y = $(this).scrollTop(); 
    if (y < $container.offset().top) { $sticky.removeClass('sticky-fixed sticky-bottom'); } 
    else if (y > length) { $sticky.attr('class','sticky sticky-bottom'); } 
    else { $sticky.attr('class','sticky sticky-fixed'); } 
}); 

的CSS:

#sticky { 
    width: 260px; 
    position: absolute; 
    right: 0; 
    top: 128px; 
    } 

#sticky-fixed { 
    position: fixed; 
    right: 0; 
    top: 128px; 
    } 

#sticky-bottom { 
    position: absolute; 
    right: 0; 
    bottom: 0; 
    top: auto; 
    } 

這裏做的事情:

如果頁面位於頂部#sticky將具有「絕對位置」,當用戶開始滾動頁面時,它將具有「位置固定」(始終在內容的側面可見),並且當視點到達底部時#container,其中的主要內容,粘性將停止在那裏。

這種方法的主要優點是「部分粘性」不會與「footer」或任何其他html元素在下面重疊。 它將在#container結束時停止,並且由於具有「固定」位置,當用戶滾動頁面時不會分散觀看者的視線。

這是我能做的最好的,看起來比我發現的其他完整腳本更容易和更輕鬆。如果它有任何錯誤或者它可以進一步更新,請改進它,讓我們知道。

由於jquery部分完成了,應該很容易適應其他人,只需將css文件屬性更改爲您的口味即可。