页面滚动时设置 div 位置

Set div position while page scrolls

我知道有人问过类似的问题,但我没见过这个。 !

我的页面上有 3 div。

WRAP 是主页面包装器,并在内部 div 周围提供边框。

OUTER 是外层 div

右边是 div 我想随着页面滚动移动。

您可以在这张图片上看到 RIGHT 所在的位置,随着页面向下滚动,我希望 right 随之移动。

我试过将 CSS 位置设置为固定,但如果调整页面大小,则会弄乱布局。我目前拥有的css是:

#wrap 
{ 
    width: 100%; 
    margin: 50px auto; 
    padding: 20px 20px 20px 20px; 
    border:2px solid #800000; 
}

#outer 
{
    margin: auto;
    width: 700px;
    height: 1250px;
    display: table;
    border: 2px solid #000008;
}

#right 
{
    float: right;
    width: 100px;
    height: 100px;
    border: 2px solid #008000;
}

我创建了一个 fiddle,目前看起来如何。

如何正确移动页面?

谢谢

position:fixed; right:0px; 添加到您的 #right div。

RouthMedia 的答案有效,但如果您有不同的限制,例如 "it shouldn't be on top of the content if the window is smaller than the layout"

为了解决这个问题,您可以使用 window.onresize 函数根据您想要的约束更改 div 的正确位置。

window.onresize = function(event) 
{
    // is the window smaller than something it shouldn't? calculate the new position
    ("#right").css("right", newpos);
};

编辑: 看到你不想把它放在外面 div。

一种方法:加载页面时,将 "right" 属性 设置为将其置于外部 div 内的内容。如果屏幕调整大小,请更新它。

另一种方法:使用 position: absolute,并在 onscroll 事件触发时用 document.scrollTop 值更新 "top" 属性。