Javascript 滚动处理程序未触发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15275969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:09:08  来源:igfitidea点击:

Javascript Scroll Handler not firing

javascriptevent-handlingdom-events

提问by Sajjan Sarkar

All I'm trying to do is to call a function when a DIVis scrolled.For simplicity sake Im not specifying anything else. Also I am only looking at DOM compliant browsers like Chrome, Safari (not IE).

我想要做的就是在 aDIV滚动时调用一个函数。为了简单起见,我没有指定任何其他内容。此外,我只关注 DOM 兼容的浏览器,如 Chrome、Safari(不是 IE)。

MY problem is that the scroll handler never gets called. If I replace the scrollto click, it works when I click. Somehow the scroll is not working.

我的问题是滚动处理程序永远不会被调用。如果我替换scrollto click,它会在我单击时起作用。不知何故,滚动不起作用。

Please note: I cannot use jQuery :(

请注意:我不能使用 jQuery :(

Here is my code:

这是我的代码:

HTML:

HTML:

<div id="test">--long content--</div>

JS:

JS:

   function myFunc() {
        console.log('in myFunc');
    }
    var objTable = document.getElementById("test");

    objTable.addEventListener("scroll", function () {
        myFunc();
    }, false);

FIDDLE:

小提琴:

http://jsfiddle.net/yymg5/7/

http://jsfiddle.net/yymg5/7/

回答by Undefined

This is because the window is scrolling not the div. Try changing your element listener to the parent of the div (in this case the window) like this.

这是因为窗口滚动而不是 div。尝试将元素侦听器更改为 div 的父级(在本例中为窗口),如下所示

window.addEventListener("scroll", function () {
    myFunc();
}, false);

回答by Vikramaditya

i had the similar issue in my case. This code is correct but was not working because,

在我的情况下,我遇到了类似的问题。此代码是正确的,但不起作用,因为,

window.addEventListener("scroll", function () {
    myFunc(); 
}, false);

scroll event wasn't firing. since my body was scrolling instead of documentElement.

滚动事件没有触发。因为我的身体在滚动而不是 documentElement。

I just removed height: 100%from my body tag and then scroll event started firing.

我刚刚height: 100%从我的 body 标签中删除,然后滚动事件开始触发。

回答by Felix Jr

I have similar issue. But in my case, I have a height: 100%on my body. Since, I just wanted to apply the scroll event in a special div only.

我有类似的问题。但就我而言,height: 100%我的身体上有一个。因为,我只想在一个特殊的 div 中应用滚动事件。

Then, this fixed the issue:

然后,这解决了问题:

document.querySelector('#myDiv').addEventListener('scroll', () => { console.log('scroll event fired!') });

document.querySelector('#myDiv').addEventListener('scroll', () => { console.log('scroll event fired!') });