【发布时间】: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