【问题标题】:Scroll event runs even though i have not scrolled即使我没有滚动,滚动事件也会运行
【发布时间】:2019-09-05 17:16:48
【问题描述】:

即使我没有滚动鼠标,控制台也会在我刷新页面后立即记录这句话“你好”。

const changeOpacity = () => {
window.onscroll = console.log('hello')}
changeOpacity();

【问题讨论】:

标签: javascript


【解决方案1】:

window.onscroll = console.log('hello') - 将立即调用console.log

您应该将赋值包装在函数声明中,如下所示:

window.onscroll = () => { console.log('hello'); }

这样每次检测到scroll 事件时都会调用您的函数。这是一个如何工作的示例:

const changeOpacity = () => {
  window.onscroll = e => { console.log(`hello ${e.detail}`); };
}

//Init the event handler
changeOpacity();

//Fire some scroll events to test our handler
for(let i = 0; i < 10; i += 1) {
  window.dispatchEvent(new CustomEvent('scroll', { detail: `scroll event ${i}` }));
}

【讨论】:

    猜你喜欢
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    相关资源
    最近更新 更多