0

向下滚动后,我试图将固定的 div 固定在顶部。

请参阅示例 - 向下滚动经过红色块后,所需的效果是绿色左列保持锚定在顶部。

示例 - 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 来做到这一点?

提前致谢

4

1 回答 1

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>

希望这有效

于 2013-08-17T08:11:57.283 回答