Javascript 如何捕获滚动事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13492656/
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
How to capture scroll event?
提问by confile
I want to implement infinite scrolling. Below is a short form of my layout. Since I have some elements relative positioned the javascript scroll event does not fire.
我想实现无限滚动。下面是我的布局的简短形式。由于我有一些相对定位的元素,因此不会触发 javascript 滚动事件。
How can I fix this problem in order to get the scroll event to be fired and implement the infinite scrolling?
如何解决此问题以便触发滚动事件并实现无限滚动?
My main layout is:
我的主要布局是:
<div id="container">
<div class="wrapper">
<div id="header">
...
</div> <%-- header --%>
<div id="main">
...
</div>
</div> <%-- wrapper --%>
</div> <%-- container --%>
<div id="footer">
</div>
And my CSS is:
我的 CSS 是:
#container {
position: absolute;
z-index: 1;
top: 0;
bottom: 35px;
left: 0;
right: 0;
overflow-y: auto;
overflow-x: hidden;
}
.wrapper {
margin: 0 auto;
width: 960px;
position: relative;
}
#header {
position: relative;
}
#main {
}
#footer {
z-index: 2;
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 35px;
}
What do I have to change such that I can receive the browser scroll event with my layout to implement infinite scrolling?
我必须更改什么才能通过布局接收浏览器滚动事件以实现无限滚动?
回答by confile
The correct way to implement it is:
正确的实现方法是:
<div id="container" onScroll="handleOnScroll();">
<script>
function handleOnScroll() {
alert("scroll");
};
</script>
回答by Sparky
EDIT: Since you tagged your question with jquery...
编辑:因为你用jquery标记了你的问题......
To capture the scrollevent using jQuery...
要scroll使用 jQuery捕获事件...
HTML:
HTML:
<div id="container">
CONTENT
</div>
jQuery:
jQuery:
$(document).ready(function() {
$('#container').scroll(function() {
alert('scroll');
// presumably your infinite scrolling code here
});
});
回答by arrest warrant
This is what i used in my code...
这是我在我的代码中使用的...
<div id="DataDiv" style="overflow: auto; width: 280px; height:400px; margin-top: 10px;"
onscroll="Onscrollfnction();">
my content here
</div>
Function is as below
功能如下
function Onscrollfnction() {
var div = document.getElementById('DataDiv');
div.scrollLeft;
return false;
};
After content crossing 400px, scrolling will start and will be infinite.. enjoy
内容越过 400px 后,滚动将开始并且将是无限的..享受

