向下滚动固定div

时间:2013-08-17 07:38:31

标签: javascript css3 css-position

我试图在向下滚动时将固定的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更实用?

提前致谢

1 个答案:

答案 0 :(得分:1)

使用此

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

并应用此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>

希望这有效