繁体   English   中英

与父容器相关的固定位置

[英]Fixed position related to the parent container

我正在使用一个非常简单的代码在滚动条上添加一个粘性元素。

我想使.top粘稠,包裹在.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');
    }
});

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%;
}

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

尝试以下CSS:

.sticky {
    position: fixed;
    width: inherit;
}

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


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

像这样

演示

CSS

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

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

.sticky{
   position: fixed;
    width: inherit;
    background-color:red;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM