[英]Scroll event bind using addEventListener on body does not work. Why?
In the following, the javascript's scroll
event does not call the function counter()
when the page is scrolled. 在下面的内容中,当页面滚动时,javascript的scroll
事件不会调用function counter()
。 Why? 为什么?
JS JS
$(function(){
var body = document.getElementsByTagName('body');
body[0].addEventListener('scroll',counter, true);
var x = 0;
function counter() {
document.getElementById("demo").innerHTML = x += 1;
}
});
HTML HTML
<div id="demo"></div>
height
property to the document, to make the scroll event actually possible 为文档设置height
属性,以使滚动事件实际上成为可能 body[0].addEventListener('scroll', counter, true)
won't make any effects. body[0].addEventListener('scroll', counter, true)
将不起作用。 body
tag is the whole document - refer to the document instead body
标签是整个文档-请参考该文档 jQuery
无需使用jQuery
就可以完成 (function() { document.addEventListener('scroll', counter, true); var x = 0; function counter() { document.getElementById("demo").innerHTML = x += 1; } })();
body { height: 1000px; } #demo { position: fixed; }
<div id="demo"></div>
Add the scroll event to the global window object and make sure that a scrollbar is actually visible so that the scroll event fires. 将滚动事件添加到全局窗口对象,并确保滚动条实际上是可见的,以便触发滚动事件。
Check the below code snippet. 检查以下代码段。
$(function() { var x = 0; window.addEventListener('scroll', counter, true); function counter() { document.getElementById("demo").innerHTML = x += 1; } });
body { height: 1000px; background-color: #E6E6E6; } #demo { position: fixed; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script> <div id="demo"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.