Home > Web Front-end > JS Tutorial > jQuery检测div中滚动条到达底部

jQuery检测div中滚动条到达底部

WBOY
Release: 2016-06-01 09:54:10
Original
1152 people have browsed it

如下检测id为scroll_div滚动条到达底部事件:

<code class="language-html"><div id="scroll_div" style="overflow-y:auto; overflowx:hidden;margin:100px;height:500px;border:1px solid red">
   <div style="height:10000px">
        来自于www.manongjc.com教程<br>
        来自于www.manongjc.com教程<br>
        来自于www.manongjc.com教程<br>
   </div>
</div></code>
Copy after login

首先需要理解几个概念:
scrollHeight:表示滚动条需要滚动的高度,即内部div,10000px
scrollTop: 表示滚动条滚动的高度,可能大于外部div 500px
也就是说scrollDiv的高度+scrollTop滚动的最大高度=scrollHeight
于是检测div中div滚动条高度就简单了:

<code class="language-javascript">$(document).ready(function() {
    $("#scroll_div").scroll(function(){
        var divHeight = $(this).height();
        var nScrollHeight = $(this)[0].scrollHeight;
        var nScrollTop = $(this)[0].scrollTop;
        $("#input1").val(nScrollHeight);
        $("#input2").val(nScrollTop);
        $("#input3").val(divHeight);
        if(nScrollTop + divHeight >= nScrollHeight) {
            alert("到达底部了");
        }
    });
});</code>
Copy after login

如果是异步加载数据,数据没加载完,又触犯了同一页的数据加载请求,我通常是加一个flag

<code class="language-javascript">$(document).ready(function() {
    var flag = false;
    $("#scroll_div").scroll(function(){
        
        if(flag){
            //数据加载中
            return false;
        }
        
        var divHeight = $(this).height();
        var nScrollHeight = $(this)[0].scrollHeight;
        var nScrollTop = $(this)[0].scrollTop;
        $("#input1").val(nScrollHeight);
        $("#input2").val(nScrollTop);
        $("#input3").val(divHeight);
        if(nScrollTop + divHeight >= nScrollHeight) {
            //请求数据
            flag = true;
            alert("到达底部了");
        }
    });
});</code>
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template