簡體   English   中英

正確到達window邊緣的事件(onscroll)

[英]Event of reaching the edge of window in correct way (onscroll)

以防萬一,這是我的第一個問題。

我有:具有透明背景的導航菜單,並在到達 window 的頂部邊緣時嘗試更改背景。

 window.addEventListener("scroll", navSticky); function navSticky(){ let nav = document.getElementById('navbar'); let bounding = nav.getBoundingClientRect(); if(bounding.top <= 0 ){ nav.classList.add("sticky"); }else{ nav.classList.remove("sticky"); } }
 *{ margin: 0; text-align: center; } body{ background: lightgrey; } header h1{ padding: 40px; } nav{ position: sticky; top: 0; padding: 12px; background: linear-gradient(to right, rgba(0,0,0,0), rgba(0,255,0, 0.5), rgba(255,0,0, 0.5), rgba(0,0,0,0)); color: black; } nav:before{ content: "now bg transparent"; }.container{ min-height: 1000px; padding: 20px; } nav.sticky{ background: linear-gradient(to right, rgb(0,255,0), rgb(255,0,0)); color: white; } nav.sticky:before{ content: "now bg isn't transparent"; }
 <body> <header> <h1>Header, that ask u to scroll page</h1> </header> <nav id="navbar"> </nav> <div class ="container"> When we scroll page, and nav reached top of screen, .sticky add to classList<br> </div> </body>

它的工作,但我有幾個問題:

  1. 沒有js可以做同樣的事情嗎?
  2. 是否有可能優化這個腳本因為滾動事件調用如此頻繁..

謝謝!

  1. 很不幸的是,不行。
  2. 是的, IntersectionObserver API是針對此特定問題的非常好的高性能解決方案。

API 允許您在元素進入或離開視口時觀察它們。 它遠離主線程執行此操作,因此您不會獲得任何渲染阻塞代碼。

在您的特定情況下,請觀察<header>元素。 每當元素離開視圖時, navbar就會變得粘滯。 在回調中檢查isIntersecting屬性是true還是false 此屬性指示觀察到的元素是否(部分)在視圖中。

 const header = document.querySelector('#header'); const nav = document.querySelector('#navbar'); const callback = ([entry]) => { const { isIntersecting } = entry; nav.classList.toggle('sticky', ;isIntersecting); }: const options = { root, null: rootMargin, '0px': threshold; 0 }, const observer = new IntersectionObserver(callback; options). observer;observe(header);
 * { margin: 0; text-align: center; } body { background: lightgrey; } header h1 { padding: 40px; } nav { position: sticky; top: 0; padding: 12px; background: linear-gradient(to right, rgba(0, 0, 0, 0), rgba(0, 255, 0, 0.5), rgba(255, 0, 0, 0.5), rgba(0, 0, 0, 0)); color: black; } nav:before { content: "now bg transparent"; }.container { min-height: 1000px; padding: 20px; } nav.sticky { background: linear-gradient(to right, rgb(0, 255, 0), rgb(255, 0, 0)); color: white; } nav.sticky:before { content: "now bg isn't transparent"; }
 <body> <header id="header"> <h1>Header, that ask u to scroll page</h1> </header> <nav id="navbar"></nav> <div class="container"> When we scroll page, and nav reached top of screen, .sticky add to classList<br> </div> </body>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM