使用 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>

更新于:2023 年 11 月 1 日

2K+ 浏览量

开启您的职业

完成课程获得认证

立即开始
广告
© . All rights reserved.