相对于父容器定位固定div

时间:2017-12-06 04:38:33

标签: jquery html css

我想在右侧边栏中添加div,这是固定的,并且相对于父容器就像这样website,请参见右侧边栏这正是我想要的网站

我尝试过很多东西,但这里没有得到任何结果是我的代码

<div id="parent_div">
 <div id="fixed_div">
  Some Content here.....
 </div>
</div>


parent_div
{
 float:right;
 width:300px;
 margin-top:50px;
 margin-right:5px;
 position:relative;
 border:1px solid red;
}

fixed_div
{
 position:fixed;
 width:300px;
 background-color:#084B8A;
 padding:10px;
 box-sizing:border-box;
}

如何在跨浏览器的css中执行此操作,如果在css中无法实现,我该如何在jquery或javascript中执行此操作

2 个答案:

答案 0 :(得分:0)

使用jquery scrollTop。看看下面的代码。

$(window).scroll(function(){
    $("#theFixed").css("top",Math.max(0,250-$(this).scrollTop()));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div id="theFixed" style="position:fixed;top:250px;right:30px;background-color:red">Fixed Div</div>

CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>CONTENT <BR>

答案 1 :(得分:0)

您可以使用position:sticky;

或者使用功能

$(window).on("scroll", function() {
    if($(window).scrollTop() > 50) {
        $(".sidebar").addClass("active");
    } else {
        //remove the background property so it comes transparent again (defined in your css)
       $(".sidebar").removeClass("active");
    }
});