简体   繁体   English

我如何获得具有由Javascript设置的固定位置的DIV,以使其保留在包含的DIV中?

[英]How do I get this DIV which has fixed position set by Javascript to stay within the containing DIV?

I have made a JSFiddle where I am trying to make a DIV stay fixed vertically in the viewport as the user scrolls, but stay under a header. 我做了一个JSFiddle ,我试图使DIV在用户滚动时垂直固定在视口中,但保持在标题下方。

However, the fixed DIV, with the green border, pops over to the right edge of the viewport when you scroll down to the point where the Javascript kicks in. 但是,当您向下滚动到插入Javascript的点时,带有绿色边框的固定DIV会弹出到视口的右边缘。

How do I constrain the green DIV so that it stays within the red bordered containing DIV? 如何约束绿色DIV,使其保持在包含DIV的红色边框内? Ideally its horizontal position would stay fixed relative to the right edge of the container. 理想地,其水平位置将相对于容器的右边缘保持固定。

CSS: 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: 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');
    }
});

Try this code. 试试这个代码。 Giving right also to your staticRight div 给予right也是你的staticRight DIV

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

Instead 代替

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

DEMO 演示

When you set an element to fixed, it gets out of the flow and hence setting the parent to relative would'nt matter. 当您将元素设置为fixed时,它会脱离流程,因此将父级设置为relative无关紧要。 The fixed div gets positioned at the desired coordinates relative to the browser window. 固定的div相对于浏览器窗口位于所需的坐标处。 So if you can calculate the left poition from the browser, just add it to your $(window).scroll when you change it to fixed. 因此,如果您可以从浏览器中计算出左位置,只需将其更改为固定位置,即可将其添加到$(window).scroll Your code should look like this- 您的代码应如下所示-

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

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

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