監聽 scroll 事件,當目標元素頂部接觸視口頂部時,切換為 position: fixed; top: 0;滾動回原位置以上時恢復靜態定位。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>滾動吸頂效果</title>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<style>
.demo {
border: 1px solid #dcdcdc; width: 300px; margin: 10px auto;
background: #fff; height: 200px; text-align: center; line-height: 200px;
}
.demo.fixed {
position: fixed;
top: 0;
left: 50%;
transform: translateX(-50%);
width: 300px;
z-index: 1000;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
background: #2196f3;
color: #fff;
}
.spacer { height: 200px; background: #f5f5f5; margin: 10px auto; width: 300px; }
</style>
</head>
<body>
1
2
3
4
我會吸頂
6
7
8
9
10