我设置了一个简单的元素示例,当您从中滚动时,该元素会粘到顶部。 https://jsfiddle.net/k9yadr8k/6/
但是,如果我将窗口调整得更小,那么内容会将元素推离窗口顶部,这会使粘性元素更早地捕捉到固定位置。所以我的问题是,如何在stickIt函数内更新窗口大小调整的offVal值?感谢
var offVal = $('#klots').offset().top;
function stickIt() {
var scrTop = $(window).scrollTop();
if (scrTop > offVal) {
$('#klots').addClass('sticky');
} else {
$('#klots').removeClass('sticky');
}
}
$(window).scroll(stickIt)
答案 0 :(得分:0)
基本上就是这样:
var $window = $(window)
var $klots = $('#klots')
var offVal = $klots.offset().top;
// listen to resize event
$window.resize(function () {
offVal = $klots.offset().top
});
function stickIt() {
var scrTop = $window.scrollTop();
if (scrTop > offVal) {
$klots.addClass('sticky');
} else {
$klots.removeClass('sticky');
}
}
$window.scroll(stickIt)