使用 Intersection Observer 檢測元素在 CSS 中以 position:sticky 固定位置
透過將各種 CSS 樣式應用到具有粘性的位置中的元素,我們可以輕鬆地檢測到元素何時被固定。
設定粘性導航欄 div
建立 div 並設定導航欄 −
<div id="first"></div> <div id="navbar-top"></div> <div id="container">Watch Me!</div> <div id="parent-container"></div>
對頂部導航欄設定樣式
設定將固定在網頁上的頂部導航欄的高度 −
#navbar-top {
background-color: lightgrey;
height: 2px;
}
使用 position fixed 設定容器 div
這將顯示檢測結果 −
#container {
position: sticky;
top: 0;
box-shadow: inset 0 0 25px navy;
height: 55px;
text-align: center;
font-size: 24x;
line-height: 55px;
font-weight: bold;
transition: font-size 0.4s ease-in;
}
設定粘性導航欄的框陰影
檢測前為導航欄設定框陰影 −
.sticky-navbar {
box-shadow: inset 0 0 15px orange!important;
font-size: 20px !important;
}
帶有 HTML DOM 的粘性導航欄指令碼
使用 HTML DOM querySelector() 並檢測在瀏覽器滾動時元素何時被固定 −
<script>
let newObserver = new IntersectionObserver(function(entries) {
if(entries[0].intersectionRatio === 0)
document.querySelector("#container").classList.add("sticky-navbar");
else if(entries[0].intersectionRatio === 1)
document.querySelector("#container").classList.remove("sticky-navbar");
}, { threshold: [0,1] });
newObserver.observe(document.querySelector("#navbar-top"));
</script>
示例
讓我們現在看一個示例來檢測元素何時被固定 −
<!DOCTYPE html>
<html>
<head>
<style>
#first {
background-color: lightgrey;
height: 10px;
}
#navbar-top {
background-color: lightgrey;
height: 2px;
}
#container {
position: sticky;
top: 0;
box-shadow: inset 0 0 25px navy;
height: 55px;
text-align: center;
font-size: 24x;
line-height: 55px;
font-weight: bold;
transition: font-size 0.4s ease-in;
}
.sticky-navbar {
box-shadow: inset 0 0 15px orange!important;
font-size: 20px !important;
}
#parent-container {
background-color: aliceblue;
height: 3300px;
}
</style>
</head>
<body>
<div id="first"></div>
<div id="navbar-top"></div>
<div id="container">Watch Me!</div>
<div id="parent-container"></div>
<script>
let newObserver = new IntersectionObserver(function(entries) {
if(entries[0].intersectionRatio === 0)
document.querySelector("#container").classList.add("sticky-navbar");
else if(entries[0].intersectionRatio === 1)
document.querySelector("#container").classList.remove("sticky-navbar");
}, { threshold: [0,1] });
newObserver.observe(document.querySelector("#navbar-top"));
</script>
</body>
</html>
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP