把你的
distanceToTop
在scroll函数之外的变量,它总是等于
y
您只需要实例化一次表标题的偏移顶部,当您向下滚动时,表的偏移顶部等于您的窗口滚动顶部。
$(document).ready(function() {
const distanceToTop = $('.table-header').offset().top; // find distance to top
$(window).on("scroll", (event) => {
const $header = $('.table-header');
const y = $(window).scrollTop(); // find current scroll position
if (y >= distanceToTop) $header.addClass('fixed');
else $header.removeClass('fixed');
});
});
$(document).ready(function() {
const distanceToTop = $('.table-header').offset().top; // find distance to top
$(window).on("scroll", (event) => {
const $header = $('.table-header');
const y = $(window).scrollTop(); // find current scroll position
if (y >= distanceToTop) $header.addClass('fixed');
else $header.removeClass('fixed');
console.log(y);
console.log(distanceToTop);
});
});
div.table {
min-height: 2000px;
background: #b0b0b0;
}
.table-header.fixed {
position: fixed;
top: 0;
width: 100%;
margin: auto;
-webkit-box-shadow: 0 3px 5px rgba(57, 63, 72, 0.3);
-moz-box-shadow: 0 3px 5px rgba(57, 63, 72, 0.3);
box-shadow: 0 3px 5px rgba(57, 63, 72, 0.3);
}
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<div class="header-container mt-5 mb-2">
<h1 class="h4">Toggle fixed class</h1>
<div class="relative text-right">
<input name="search-input" id="search-input" class="" type="search" placeholder="Search a contact ...">
</div>
</div>
<div class="table">
<div class="table-row table-header relative bg-primary text-light mb-1">
Fixed div
</div>
<div id="contacts-list" class="">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
真希望我帮了你