2013-08-17 60 views
0

我試圖在滾動時將固定的div粘貼到頂部。在向下滾動時粘貼固定div

請參閱示例 - 一旦您向下滾動過紅色塊,綠色左側欄將保持錨定在頂部。

Example - JS FIDDLE

HTML

<div id="block">block</div> 

<div id="content"> 
<div id="left">fixed</div> 
<div id="right"> 
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque consequat neque ac diam pulvinar aliquet. Sed cursus mauris a ipsum ultricies malesuada. Integer vel velit accumsan, sagittis ipsum et, lacinia tellus.</p> 
    <p>Praesent consequat lacus sed dui sagittis, nec interdum tellus viverra. Donec tincidunt augue justo, in eleifend leo rutrum id. Nam feugiat iaculis neque a tincidunt. In condimentum tortor quis vestibulum pharetra. Vestibulum in elit ut tortor ultricies faucibus a eu augue. Quisque dignissim nec nibh non malesuada.</p> 
    <p>In ligula tellus, facilisis ac purus sed, congue congue justo. Aliquam consequat nunc lorem, nec mattis lorem facilisis quis. Aliquam vel eleifend nunc.</p> 
    <p>Praesent consequat lacus sed dui sagittis, nec interdum tellus viverra. Donec tincidunt augue justo, in eleifend leo rutrum id. Nam feugiat iaculis neque a tincidunt. In condimentum tortor quis vestibulum pharetra. Vestibulum in elit ut tortor ultricies faucibus a eu augue. Quisque dignissim nec nibh non malesuada.</p> 
    <p>In ligula tellus, facilisis ac purus sed, congue congue justo. Aliquam consequat nunc lorem, nec mattis lorem facilisis quis. Aliquam vel eleifend nunc.</p> 
</div> 
</div> 

CSS

#block { 
    background: #B84B3D; 
    width: 100%; 
    height: 200px; 
    position: fixed; 
    z-index: 0; 
    font-size: 16px; 
    color: #fff; 
    text-align: right; 
} 
#content { 
    margin-top: 160px; 
    float: left; 
} 
#left { 
    background: #73CC66; 
    width: 50%; 
    height: 100%; 
    font-size: 16px; 
    color: #fff; 
    position: absolute; 
} 
#right { 
    background-color: rgba(255,255,255,0.8); 
    width: 50%; 
    float: right; 
    color: #ccc; 
    z-index: 10; 
    position: relative; 
} 

有沒有辦法用CSS或更多的實用性和JS做到這一點?

在此先感謝

+0

這隻能用JavaScript實現。將一個處理程序附加到onscroll事件,並在屏幕滾動經過某個點時將「位置」更改爲固定,並在屏幕達到特定點以上時設置「位置」以阻止。那裏有很多例子。 – Sumurai8

+0

@ Sumurai8我認爲你的意思是「並將'位置'設置爲相對/絕對」而不是「並設置'位置'來阻止」 – FakeRainBrigand

+0

@FakeRainBrigand Yup;這就是我derping – Sumurai8

回答

1

與此

#left { 
    background: #73CC66; 
    width: 50%; 
    height: 300px; 
    font-size: 16px; 
    color: #fff; 
    float:left; 
    position: static; 
} 

修改CSS並應用此javascript

<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript" ></script> 
<script> 
window.onscroll = function(){ 
    if(window.XMLHttpRequest) { 
     var position=window.pageYOffset; 
     if (position > 160) { 
      $('#left').css({'position':'fixed', 'top':'0' }); 
      } else { 
      $('#left').css({'position':'static', 'top':'auto' }); 
     } 
    } 
} 
</script> 

希望這個作品

+0

這看起來不錯。我更新了jsfiddle,但似乎無法在向下滾動時扭轉效果。 – Rob

+0

你是否修改了你的css –

+0

是的,看到jsfiddle http://jsfiddle.net/Bxa4C/4/ – Rob