我做了一个JSFiddle当用户滚动时,我试图使 DIV 在视口(viewport)中垂直固定,但保留在标题下。
但是,当您向下滚动到 Javascript 开始的位置时,带有绿色边框的固定 DIV 会弹出到视口(viewport)的右边缘。
如何限制绿色 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');
}
});
最佳答案
试试这段代码。将 right
也赋予你的 staticRight
div
$('#staticRight').css('position', 'fixed').css('top', '0').css('right','20px');
代替
$('#staticRight').css('position', 'fixed').css('top', '0');
关于javascript - 如何让这个由 Javascript 设置固定位置的 DIV 留在包含的 DIV 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25174140/