为什么';当我滚动到我的网页div类的某个点时,javascript会执行吗?

为什么';当我滚动到我的网页div类的某个点时,javascript会执行吗?,javascript,html,Javascript,Html,Html: 只需将scroll事件添加到div中,这可能甚至无法滚动。这样做行不通,您需要将其添加到窗口/文档中,并检测元素是否在视图端口中,然后执行操作,在这个链接上,您有两个解决方案如何: <div class="counter" data-target="3"> -1 </div> $('.domo

Html:


只需将scroll事件添加到div中,这可能甚至无法滚动。这样做行不通,您需要将其添加到窗口/文档中,并检测元素是否在视图端口中,然后执行操作,在这个链接上,您有两个解决方案如何:
                    <div class="counter" data-target="3">
                        -1
                    </div>
$('.domov2').scroll(function() {

const counters = document.querySelectorAll('.counter');

counters.forEach(counter => {
    
    const updateCount = () => {
        const target = +counter.getAttribute('data-target');
        const count = +counter.innerText;
        
        // Check if target is reached
        if (count < target) {
            // Add inc to count and output in counter
            var sestevek = count + 1
            
            counter.innerText = sestevek;
            // Call function every ms
            setTimeout(updateCount, 300);
        } else {
            counter.innerText = target;
        }
    };

    updateCount();
});

});