与父容器相关的固定位置 [英] Fixed position related to the parent container

查看:114
本文介绍了与父容器相关的固定位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用一个非常简单的代码在滚动时创建一个粘性元素。



我想使.top粘性,它包裹在.wrap。
当我向下滚动时,我想设置.top相对于wrap的位置(所以它从左开始:0与.wrap相关,与body无关,我想将它保存在








  var top = $('。top')。offset()。top; 
$(window).scroll(function(event){
var y = $(this).scrollTop();
if(y> = top){
$('top')。addClass('sticky');
}
else {
$('。top')。removeClass('sticky');
}
});
pre>

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:

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

DEMO: http://jsfiddle.net/63cFy/1/






PS:作为 @ jsmorph 提到您还可以添加 top:0 使元素看起来更好滚动。


I'm using a very simple code to make a sticky element on scroll.

I want to make .top sticky, which is wrapped inside .wrap. When I scroll down, I want to set the position of .top related to the wrap (so that it starts from left: 0 related to the .wrap, not related to the body. I want to keep it inside the .wrap only. How can I do that? Thanks.

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

Demo: http://jsfiddle.net/63cFy/

解决方案

Try the following CSS:

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

DEMO: http://jsfiddle.net/63cFy/1/


P.S: As @jsmorph mentioned you could also add top: 0 to make the element look better on scrolling.

这篇关于与父容器相关的固定位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆