问题描述
我要做的就是在滚动 DIV
时调用一个函数.为简单起见,我没有指定其他任何内容.此外,我只关注 DOM 兼容的浏览器,例如 Chrome、Safari(不是 IE).
All I'm trying to do is to call a function when a DIV
is scrolled.For simplicity sake Im not specifying anything else. Also I am only looking at DOM compliant browsers like Chrome, Safari (not IE).
我的问题是滚动处理程序永远不会被调用.如果我将 scroll
替换为 click
,它会在我单击时起作用.不知何故,滚动不起作用.
MY problem is that the scroll handler never gets called. If I replace the scroll
to click
, it works when I click. Somehow the scroll is not working.
请注意:我不能使用 jQuery :(
Please note: I cannot use jQuery :(
这是我的代码:
HTML:
<div id="test">--long content--</div>
JS:
function myFunc() {
console.log('in myFunc');
}
var objTable = document.getElementById("test");
objTable.addEventListener("scroll", function () {
myFunc();
}, false);
小提琴:
http://jsfiddle.net/yymg5/7/
推荐答案
这是因为窗口滚动而不是div.尝试将您的元素侦听器更改为 div 的父级(在本例中为窗口),例如 this.
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.
window.addEventListener("scroll", function () {
myFunc();
}, false);
这篇关于Javascript 滚动处理程序未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!