固定位置不适用于我的用例,因为它固定在浏览器窗口中,您可能会处于文本离开屏幕右侧而无法访问的状态。无论如何,我尝试使用绝对定位,然后在 javascript 中调整“顶部”。它在 Firefox 和 Chrome 中运行良好,但在 Safari 中滚动时内容会抖动。
<div class="fixed sticky" data-offset-top="50"><p>fixed</p></div>
$(document).ready(function() {
var documentHeight = $(document).height();
$(document).scroll(function() {
var scrollTop = $(window).scrollTop();
$(".sticky").offset(function() {
$this = $(this);
var offsetTop = $this.data("offset-top");
if (scrollTop < 0) {
scrollTop = 0;
}
var newTop = offsetTop + scrollTop;
if (newTop < offsetTop) {
newTop = offsetTop;
}
// Prevents document from infinitely expanding.
var maxTop = documentHeight - $this.height();
if (newTop > maxTop) {
newTop = maxTop
}
// Prevents a bit of jitter since the current offset can be
// not precisely the initial offset. 338 Vs. 338.12931923
var currentTop = $this.offset().top;
if ( Math.abs(currentTop - newTop) >= 1 ) {
return { top: newTop }
} else {
return {}
}
});
});
})