<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
body{
height: 1800px;
}
#box1,#box2{
display: inline-block;
width: 100px;
height: 100px;
}
#box1{
background-color: red;
}
#box2{
background-color: orange;
position: fixed;
}
</style>
<script src="../js/jquery-3.5.1.js"></script>
<script>
$(function () {
//滚动事件
//固定栏目
//获取box2距离顶部的距离
var top = $("#box2").offset().top;
//根据滚动判断定位
$(window).scroll(function () {
if($(this).scrollTop() > top)
{
//当滚动条距离超过box2的位置时,设定为固定定位
$("#box2").css({
"position":"fixed",
"top":"0"
});
}
else
{
//滚动条的距离小于box2的位置时,设定为相对定位
$("#box2").css({
"position":"relative",
});
}
});
});
</script>
</head>
<body>
<div id="box1"></div><br>
<div id="box2"></div>
</body>
</html>