Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

200
Views
Cómo usar el observador de intersección para agregar clase a elemento hasta que se alcance el siguiente elemento, luego agregar clase a ese, etc.

Quiero usar un observador de intersección para ver cuándo se ha llegado a cierta parte de mi página. Mi página está dividida por algunas secciones con identificadores, por ejemplo, #sección1, #sección2, #sección3, etc.

En la parte superior de mi página hay un menú fijo con botones para navegar a cada sección. Quiero resaltar el botón que un usuario está viendo actualmente.

Entonces, cuando se desplace a la sección 1, resalte el botón de la sección 1, pero cuando se desplace hacia abajo, manténgalo resaltado hasta que se alcance la sección 2 (con un pequeño desplazamiento, tal vez 300 px para que el usuario se desplace un poco más allá del divisor hasta que se resalte), luego resalte ese botón .

¿Cómo se puede hacer esto?

Yo hice esto:

 function selectElementById(idname) { return document.querySelector(`#${idname}`); } const sections = [ selectElementById('top'), selectElementById('bestellen'), selectElementById('informatie'), selectElementById('inspiratie'), selectElementById('reviews'), ]; const navItems = { top: selectElementById('topbtn'), bestellen: selectElementById('bestellenbtn'), informatie: selectElementById('informatiebtn'), inspiratie: selectElementById('inspiratiebtn'), reviews: selectElementById('reviewsbtn'), }; const observerOptions = { root: null, rootMargin: '-175px 0px 0px 0px', threshold: 0.7, }; function observerCallback(entries, observer) { entries.forEach((entry) => { if (entry.isIntersecting) { // get the nav item corresponding to the id of the section // that is currently in view const navItem = navItems[entry.target.id]; // add 'active' class on the navItem navItem.classList.add('activeprodmenu'); // remove 'active' class from any navItem that is not // same as 'navItem' defined above Object.values(navItems).forEach((item) => { if (item != navItem) { item.classList.remove('activeprodmenu'); } }); } }); } const observer = new IntersectionObserver(observerCallback, observerOptions); sections.forEach((sec) => observer.observe(sec));

Pero recibo este error: Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!