How to capture scroll event?

依然范特西╮ 提交于 2019-12-01 15:49:01

问题


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.

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:

#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?


回答1:


The correct way to implement it is:

 <div id="container" onScroll="handleOnScroll();">

<script>
function handleOnScroll() {
        alert("scroll");
    };
</script>



回答2:


EDIT: Since you tagged your question with jquery...


To capture the scroll event using jQuery...

HTML:

<div id="container">
    CONTENT
</div> 

jQuery:

$(document).ready(function() {

    $('#container').scroll(function() {
        alert('scroll');
        // presumably your infinite scrolling code here
    });

});

See: http://api.jquery.com/scroll/




回答3:


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



来源:https://stackoverflow.com/questions/13492656/how-to-capture-scroll-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!