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

258
Views
Agregar clase a un div cuando otro está en la ventana gráfica

Tengo un sitio web que usa el complemento de desplazamiento vertical. El sitio web está dividido en secciones de ancho y alto completo y me gustaría diseñar la navegación y otros elementos según cuál de estas secciones esté en la ventana gráfica.

He intentado muchas respuestas que he encontrado en línea sin éxito. Lo más cerca que puedo hacer que funcione es esto:

 var targets = document.querySelectorAll('section') var obsOptions = { root: null, // measure against the viewport threshold: .5 // how much of the element should be visible before handler is triggered } let handler = (entries, opts) => { entries.forEach(entry => { if (entry.intersectionRatio > opts.thresholds[0]) { document.body.classList.remove(...document.body.classList); document.body.classList.add(entry.target.id + '-active'); } }) } targets.forEach(el => { var observer = new IntersectionObserver(handler, obsOptions); observer.observe(el); })

Esto funciona bien, excepto que elimina todas las clases del cuerpo y el tema de WordPress agrega las propias, que son necesarias para que funcione, así que no puedo tener eso.

Si elimino la línea sobre la eliminación de las clases, TODAS las ID de la sección se muestran como clases al mismo tiempo.

Pensé que la mejor manera sería no aplicarlo al cuerpo, sino a un contenedor que no tenía otras clases, así que envolví todo en un contenedor div con una clase de

 .full-page-container

Traté de editar el código a este

 var targets = document.querySelectorAll('section') var obsOptions = { root: null, // measure against the viewport threshold: .5 // how much of the element should be visible before handler is triggered } let handler = (entries, opts) => { entries.forEach(entry => { if (entry.intersectionRatio > opts.thresholds[0]) { document.full-page-container.classList.remove(...document.ful-page-container.classList); document.full-page-container.classList.add(entry.target.id + '-active'); } }) } targets.forEach(el => { var observer = new IntersectionObserver(handler, obsOptions); observer.observe(el); })

pero no funciona

¿Cómo se aplica este mismo efecto a un div en lugar del cuerpo?

Cualquier ayuda sería muy apreciada

Aquí hay un codepen que he reunido.

https://codepen.io/shereewalker/pen/bGaqqmy

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

En la eliminación, está gastando el contenido de classList y creo que, por lo tanto, está eliminando todas las clases.

Sugeriría filtrar classList para las clases que contienen -active (La clase que agrega) y luego eliminarlas.

 var targets = document.querySelectorAll('section') var obsOptions = { root: null, // measure against the viewport threshold: .5 // how much of the element should be visible before handler is triggered } let handler = (entries, opts) => { entries.forEach((entry) => { if (entry.intersectionRatio > opts.thresholds[0]) { const classesToRemove = findClassesWithActive(document.body.classList); if (classesToRemove.length > 0) { document.body.classList.remove(classesToRemove); } document.body.classList.add(entry.target.id + "-active"); } }); }; targets.forEach(el => { var observer = new IntersectionObserver(handler, obsOptions); observer.observe(el); })
 function findClassesWithActive(classList) { return classList.filter(c => c.includes('-active') }

Codepenne con él funcionando

about 4 years ago · Juan Pablo Isaza Report
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!