【问题标题】:How to call a function, when page is scrolled to certain element?当页面滚动到某个元素时,如何调用函数?
【发布时间】:2021-02-15 19:48:10
【问题描述】:

你能告诉我为什么我的代码不起作用。我想在页面滚动到某个元素时调用一个函数。 (我想在不使用 jQuery 的情况下在 vanilla js 中找到解决方案)

const numberContainer = document.querySelector('.numbers');

window.addEventListener('scroll', () => {
    const scrolled = window.scrollY;
    const elementPosition = numberContainer.scrollY;
    
    if(scrolled == elementPosition){
        counter();
    }
})

【问题讨论】:

标签: javascript html css function scroll


【解决方案1】:

尝试使用 offsetTop 作为 numberContainer

const elementPosition = numberContainer.offsetTop;

【讨论】:

    【解决方案2】:

    HTMLElement(在您的情况下为numberContainer)上没有名为scrollY 的属性。 offsetTop 是您要查找的属性。

    更多信息在这里 - https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop

    【讨论】:

      猜你喜欢
      • 2018-01-26
      • 1970-01-01
      • 2021-03-21
      • 1970-01-01
      • 2016-10-22
      • 1970-01-01
      • 1970-01-01
      • 2011-11-27
      • 2021-04-07
      相关资源
      最近更新 更多