分享一個移動端滑到底部翻頁的代碼

今天在技術羣看到有朋友有需求,就隨手寫了一個,你們隨便看看~
demo地址:http://www.dtzhuanjia.com/pri...
(備註:這個主要用在移動端,因此用rem隨便寫了寫樣式= =PC看着不舒服用模擬器看吧)php

html:css

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>下一頁</title>    
    <meta name="Keywords" content="">
    <meta name="description" content="">
    <meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width">
    <link rel="stylesheet" href="http://www.dtzhuanjia.com/css/init.css">
    <link rel="stylesheet" href="http://www.dtzhuanjia.com/private/plugin/nextpage/index.css">
</head>
<body>
    <script src="http://www.dtzhuanjia.com/js/calrem.js"></script>
    <style>
    .block{width:100%;height:4rem;line-height:4rem; background:#ccc;text-align:center;font-size:1rem;color:#fff;border-bottom:}
    </style>
    <div class="main">
        <div class="block">已經加載的1-1</div>
        <div class="block">已經加載的1-2</div>
        <div class="block">已經加載的1-3</div>
        <div class="block">已經加載的1-4</div>
        <div class="block">已經加載的1-5</div>
    </div>
    
    <script src="http://www.dtzhuanjia.com/js/basic/jquery.js"></script>
    <script src="http://www.dtzhuanjia.com/private/plugin/nextpage/index.js"></script>
    <script>
    $(document).ready(function(){
        var initNextPage = new InitNextPage({
            bottom : 20,//距離底部像素
            target : ".main",//插入目標源
            url : "http://www.dtzhuanjia.com/private/plugin/nextpage/nextPage.php"//ajax請求的url
        })
    });
    </script>
</body>
</html>

js代碼:html

function InitNextPage(obj){
    _this = this;
    _this.bottom = obj.bottom||10;//距離底部像素
    _this.target = obj.target||"body";//插入目標源
    _this.url = obj.url||"none";//ajax請求的url
    _this.page = 2;
    //滑到底
    $(window).scroll(function(){
        _this.scrollToBottom();
    });    
}
InitNextPage.prototype = {
    scrollToBottom : function(){
        if($(window).scrollTop()+$(window).height()>$(document).height()-_this.bottom){
            if(_this.url=="none"){
                alert("ajax url不能爲空");
                return;
            }
            $.ajax({
                url : _this.url,
                async: false,
                data : {
                    page : _this.page,
                },
                success : function(data){
                    _this.page++;
                    $(_this.target).append(data);
                }
            });
        }
    }
}

備註:jquery

var initNextPage = new InitNextPage({
    bottom : 20,//距離底部像素
    target : ".main",//插入目標源
    url : "http://www.dtzhuanjia.com/private/plugin/nextpage/nextPage.php"//ajax請求的url
})

上面代碼中:
bottom是距離底部多少像素時執行ajax,默認10
target是執行成功後,像哪一個dom插入返回的數據,默認爲body
url是ajax url地址,必填。ajax

若是有其餘需求,好比返回json(例子中直接返回Html),能夠修改success中的代碼,就不贅述了~chrome

相關文章
相關標籤/搜索