【问题标题】:How do I get this DIV which has fixed position set by Javascript to stay within the containing DIV?如何让这个由 Javascript 设置的固定位置的 DIV 保持在包含的 DIV 内?
【发布时间】:2014-08-07 21:29:54
【问题描述】:

我创建了一个JSFiddle,我试图让 DIV 在用户滚动时保持垂直固定在视口中,但保持在标题下方。

但是,当您向下滚动到 Javascript 启动的位置时,带有绿色边框的固定 DIV 会弹出到视口的右边缘。

如何限制绿色 DIV 使其保持在包含 DIV 的红色边框内?理想情况下,它的水平位置将相对于容器的右边缘保持固定。

CSS:

header {
   width: 100%;
    height: 10em;
    border: purple thin solid;
}
#container {
    border: thin solid red;
    position: relative;
    height: 100%;
    max-width:30em;
    margin: 0 auto 0 auto;
}
#staticRight {
    border: green thin solid;
    display: inline-block;
    float: right;
    right: 0;
    margin: 2em 0 0 0;
    width: 120px;
    height:600px;
    font-size: .82em;
    line-height:2em;
}
article {
    border: blue thin solid;
    max-width: 20em;
}

Javascript:

var elementPosition = $('#staticRight').offset();
$(window).scroll(function () {
    if ($(window).scrollTop() > elementPosition.top) {
        $('#staticRight').css('position', 'fixed').css('top', '0');

    } else {
        $('#staticRight').css('position', 'static');
    }
});

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    试试这个代码。将right 也提供给您的staticRight div

    $('#staticRight').css('position', 'fixed').css('top', '0').css('right','20px');
    

    相反

    $('#staticRight').css('position', 'fixed').css('top', '0');
    

    DEMO

    【讨论】:

    • 感谢您的回复,但是当我查看您的 JSFiddle 时,我没有发现任何与原始行为不同的行为。
    【解决方案2】:

    当您将元素设置为固定时,它会脱离流程,因此将父级设置为相对无关紧要。固定的 div 被定位在相对于浏览器窗口的所需坐标处。因此,如果您可以从浏览器计算左侧位置,只需将其添加到您的$(window).scroll,然后将其更改为固定即可。您的代码应如下所示-

    <div id="staticRight" style="position: fixed; top: 0px; left: 70%;"></div>

    【讨论】:

    • 感谢您的回复。因为布局是响应式和流畅的,我不知道我是否可以依靠左侧位置的计算。但是,我不需要 DIV 使用固定位置。如果有其他方法可以让用户滚动 div,无论是使用 Javascript 还是其他任何方法,我都愿意接受任何方法。
    • 好吧,如果它是响应式的,我能想到的最简单的方法是在所有媒体查询断点中添加右/左。像 -@media screen 和 (min-width:767px) { #staticRight { position: fixed;对:20%; } }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-07
    • 1970-01-01
    • 1970-01-01
    • 2011-12-23
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多