javascript - 固定内容的位置,直到父 div 结束
问题描述
我有一段代码在 y-scoll 超过 765px 时得到修复。问题是即使在其父级之外,此内容也会被修复。这是一个例子:https ://jsfiddle.net/rwbsua3v/
如您所见,当您继续滚动时,绿色框中的内容会被固定,并会在您滚动时覆盖蓝色框。
如果我知道红色/绿色和蓝色框的确切高度,我可以解决这个问题,但问题是它们可以是任意长度。如何在不影响 y-scroll 偏移和 css top: 87px 的情况下固定绿色框中的内容直到它到达父级(绿色框)的底部?
这是我的代码:
window.onscroll = function() {
myFunction()
};
var floating1 = document.getElementById("floating1");
var yOffset = 765;
function myFunction() {
if (window.pageYOffset > yOffset) {
floating1.classList.add("sticky");
} else {
floating1.classList.remove("sticky");
}
}
table {
width: 100%;
min-height: 2000px;
}
table tr td {
vertical-align: top;
}
.sticky {
position: fixed!important;
top: 87px;
}
<table>
<tr>
<td style="background: red; width: 200px;">
...
</td>
<td style="background: green; width: 200px;">
<div id="floating1">
Floating content
</div>
</td>
</tr>
</table>
<div style="height: 1500px; background: blue;">
...
</div>
解决方案
使用position: sticky
它使元素固定到位,直到它遇到它的容器边缘:
window.onscroll = function() {
myFunction()
};
var floating1 = document.getElementById("floating1");
var yOffset = 765;
function myFunction() {
if (window.pageYOffset > yOffset) {
floating1.classList.add("sticky");
} else {
floating1.classList.remove("sticky");
}
}
table {
width: 100%;
min-height: 2000px;
}
table tr td {
vertical-align: top;
}
.sticky {
position: sticky;
top: 87px;
}
<table>
<tr>
<td style="background: red; width: 200px;">
...
</td>
<td style="background: green; width: 200px;">
<div id="floating1">
Floating content
</div>
</td>
</tr>
</table>
<div style="height: 1500px; background: blue;">
...
</div>