在現在用 css 的 position: sticky 就可以設定當區塊超過可視範圍後就卡在頁面上某處的效果,不過如果除了卡住外還想修改樣式,就還是得用 javascript 來處理。

這邊先把 css sticky 的 top 設定成 -1px,這樣可以讓這區塊超出可視範圍。

.nav {
  position: sticky;
  top: -1px;
}

/* styles for when the header is in sticky mode */
.nav.active {
  background: rgba(0,0,0,.8);
} 

 

接著利用 js 的 IntersectionObserver 來偵測目標區塊後判斷是否要添加 class,會比 scroll 事件效能好很多。

const el = document.querySelector(".nav")
const observer = new IntersectionObserver( 
  ([e]) => e.target.classList.toggle("active", e.intersectionRatio < 1),
  { threshold: [1] }
);

observer.observe(el);

效果可以參考這頁

 

參考文章:
position:sticky : Adding style when the element detaches from normal flow