修复与父容器相关的位置

use*_*640 0 html javascript css jquery

我正在使用一个非常简单的代码在滚动上制作一个粘性元素.

我想制作.top sticky,它包裹在.wrap中.当我向下滚动时,我想设置与包裹相关的.top的位置(这样它从左边开始:0与.wrap相关,与身体无关.我想把它保留在.wrap中.我怎么能这样做?谢谢.

jQuery的:

var top = $('.top').offset().top;
$(window).scroll(function (event) {
    var y = $(this).scrollTop();
    if (y >= top){
        $('.top').addClass('sticky');
    }
    else{
        $('.top').removeClass('sticky');
    }
});
Run Code Online (Sandbox Code Playgroud)

CSS:

.wrap{
    width: 300px;
    border: 1px solid green;
    margin: 0 auto;
    height: 1000px;
}

.top{
    background: green;
    height: 100px;
}

.sticky{
    position: fixed;    
    top: 0;
    left: 0;
    width: 100%;
}
Run Code Online (Sandbox Code Playgroud)

演示: http ://jsfiddle.net/63cFy/

Vis*_*ioN 5

尝试以下CSS:

.sticky {
    position: fixed;
    width: inherit;
}
Run Code Online (Sandbox Code Playgroud)

演示: http ://jsfiddle.net/63cFy/1/


PS:正如@jsmorph所提到的,您还可以添加top: 0以使元素在滚动时看起来更好.