[英]Div stops at the top when scrolling
我試圖使div更改類在到達頁面頂部時固定。
我有這個JavaScript代碼。
<script type="text/javascript">
$(function () {
var top = 200;
var y = $(this).scrollTop();
if (y >= top) {
// if so, add the fixed class
$('#kolonne-v').addClass('fixed');
} else {
// otherwise remove it
$('#kolonne-v').removeClass('fixed');
}
});
</script>
我究竟做錯了什么?
JS
$(function () {
var top = 200;
//this should be the offset of the top of your div
//which can be found by doing the following line
//var top = $("#kolonne-v").offset().top;
$(window).on('scroll', function () {
if (top <= $(window).scrollTop()) {
// if so, add the fixed class
$('#kolonne-v').addClass('fixed');
} else {
// otherwise remove it
$('#kolonne-v').removeClass('fixed');
}
})
});
描述
這使用jquery .on('scroll', handler)
方法, 在此提供文檔 。 基本原理是在document.ready
上,當div固定在頂部時,設置滾動點。 然后,設置一個.on('scroll', handler)
事件,該事件在滾動窗口時觸發。如果用戶滾動到您的位置,則添加fixed
CSS類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.