使内容在滚动到 jQuery 中的某个点时保持粘性
Make content sticky on scroll to a point in jQuery
我有一个 div
设置为 position: relative
。当 window 的顶部到达它时,它变为 fixed
。 div 位于容器中(下例中为蓝色),当它到达其父容器(蓝色)的底部时,我想将其设置回 relative
。
这是我的代码简化和我的 Fiddle:
HTML:
<div class="green"></div>
<div class="blue">
<div class="sticky">Sticky</div>
</div>
<div class="red"></div>
CSS:
.blue {
background-color: blue;
height: 500px;
}
.sticky {
width: 200px;
background-color: yellow;
text-align: center;
top: 0;
}
.red {
background-color: red;
height: 800px;
}
.green {
background-color: green;
height: 200px;
}
和jQuery:
$(document).ready(function() {
var stickyTop = $('.sticky').offset().top;
$(window).scroll(function() {
var windowTop = $(window).scrollTop();
if (stickyTop < windowTop) {
$('.sticky').css('position', 'fixed');
} else {
$('.sticky').css('position', 'relative');
}
});
});
将以下条件添加到您的 if
语句中:
$(".blue").height() + $(".blue").offset().top > windowTop
您的代码应如下所示:
$(document).ready(function() {
var stickyTop = $('.sticky').offset().top;
$(window).scroll(function() {
var windowTop = $(window).scrollTop();
if (stickyTop < windowTop && $(".blue").height() + $(".blue").offset().top - $(".sticky").height() > windowTop) {
$('.sticky').css('position', 'fixed');
} else {
$('.sticky').css('position', 'relative');
}
});
});
解决方法如下:
$(window).scroll(function() {
var navpos1 = $('.header').offset().top();
if (navpos1) {
$('body').addClass('fixedHd');
} else {
$('body').removeClass('fixedHd');
}
});
你可以使用 jquery.sticky.js 插件
为要粘贴的元素添加一个id
$('#sticky').sticky();
我有一个 div
设置为 position: relative
。当 window 的顶部到达它时,它变为 fixed
。 div 位于容器中(下例中为蓝色),当它到达其父容器(蓝色)的底部时,我想将其设置回 relative
。
这是我的代码简化和我的 Fiddle:
HTML:
<div class="green"></div>
<div class="blue">
<div class="sticky">Sticky</div>
</div>
<div class="red"></div>
CSS:
.blue {
background-color: blue;
height: 500px;
}
.sticky {
width: 200px;
background-color: yellow;
text-align: center;
top: 0;
}
.red {
background-color: red;
height: 800px;
}
.green {
background-color: green;
height: 200px;
}
和jQuery:
$(document).ready(function() {
var stickyTop = $('.sticky').offset().top;
$(window).scroll(function() {
var windowTop = $(window).scrollTop();
if (stickyTop < windowTop) {
$('.sticky').css('position', 'fixed');
} else {
$('.sticky').css('position', 'relative');
}
});
});
将以下条件添加到您的 if
语句中:
$(".blue").height() + $(".blue").offset().top > windowTop
您的代码应如下所示:
$(document).ready(function() {
var stickyTop = $('.sticky').offset().top;
$(window).scroll(function() {
var windowTop = $(window).scrollTop();
if (stickyTop < windowTop && $(".blue").height() + $(".blue").offset().top - $(".sticky").height() > windowTop) {
$('.sticky').css('position', 'fixed');
} else {
$('.sticky').css('position', 'relative');
}
});
});
解决方法如下:
$(window).scroll(function() {
var navpos1 = $('.header').offset().top();
if (navpos1) {
$('body').addClass('fixedHd');
} else {
$('body').removeClass('fixedHd');
}
});
你可以使用 jquery.sticky.js 插件
为要粘贴的元素添加一个id
$('#sticky').sticky();