【问题标题】:Position fixed div with relative to the parent container相对于父容器定位固定 div
【发布时间】:2020-08-31 01:01:29
【问题描述】:

我想在右侧边栏中添加一个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 中执行此操作

【问题讨论】:

  • 你有一个你想要的例子。正常的做法是弄清楚他们是如何做你想做的事情的。您可以通过查看浏览器的开发工具并查看它们使用的 CSS/HTML/JavaScript 来做到这一点。
  • 您可以尝试给元素 position:sticky; top:0 - 否则按照示例页面上的操作 - 更新元素 CSS onscroll。

标签: jquery html css


【解决方案1】:

利用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>

【讨论】:

    【解决方案2】:

    你可以使用 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");
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-12
      • 2011-08-17
      • 1970-01-01
      • 2015-10-29
      • 2019-02-18
      • 2011-10-11
      • 2016-08-17
      • 1970-01-01
      相关资源
      最近更新 更多