Estoy tratando de manipular un objeto de destino usando la API del observador de intersección una vez que 0.5 de él están dentro de la ventana gráfica que en realidad parece funcionar. Sin embargo, la función de devolución de llamada también se activa directamente al cargar la página y parece que también se activa una vez que se desplaza hacia arriba, ¿por qué?
let options = { root: null, // set the root rootMargin: '0px', threshold: 0.5 // 1.0 means 100% of target has to be visible to trigger callback }; // Declare the target element to manipulate const target = document.querySelector('.target'); let callback = (entries, observer) => { entries.forEach(entry => { target.classList.toggle( 'target-hit' , entries[0].isIntersecting ); console.log('fired') }); }; // Create intersection observer let observer = new IntersectionObserver(callback, options); // Initiate observer to watch for target observer.observe( target ); .non-target { height: 1000px } .target { background-color: red; width: 40px; height: 40px; margin-bottom: 30px; } .target-hit { background-color: green } <div class="non-target">Non-Target - Please scroll down to target :)</div> <div class="target">Target</div>