Loading

js上拉加载、下拉刷新的插件

之前在网上找那种下拉刷新,上拉加载的插件,有一款IScroll,但是用起来太麻烦,于是就自己写了款,但依赖于jquery.js,bug肯定有,希望评论提出。

推荐一个简洁且文档的插件:传送门

因为我这个不算一个很稳定的东西,只是大概能用
js:

/*
    简洁的下拉刷新,上拉加载插件
    Author:myEsn2E9
    QQ:865540141
    Date:2016-5-17
*/

; !(function () {
    var defaultParame = {
        positionY: 0,
        positionTop: 0,
        positionBottom: 0,
        screenY: 0,
        topSpeed: .6,
        animateSpeed: 800,
        whenThisHeightExecuteCallback: 50,
        refreshDom: {
            prop: '.refresh',
            startText: '下拉刷新',
            ingText: '更新中',
            endText: '释放更新'
        },
        loadDom: {
            prop: '.load',
            startText: '上拉加载',
            ingText: '加载中',
            endText: '释放加载'
        },
        isStartRefresh: false,
        isStartLoad: false,
        isRefreshIng: false,
        isLoadIng: false,
        moveArray: new Array(),
        continueMoveDirection: '',
        loadImg: {
            src: 'data:image/gif;base64,R0lGODlhIAAgALMAAP///7Ozs/v7+9bW1uHh4fLy8rq6uoGBgTQ0NAEBARsbG8TExJeXl/39/VRUVAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFBQAAACwAAAAAIAAgAAAE5xDISSlLrOrNp0pKNRCdFhxVolJLEJQUoSgOpSYT4RowNSsvyW1icA16k8MMMRkCBjskBTFDAZyuAEkqCfxIQ2hgQRFvAQEEIjNxVDW6XNE4YagRjuBCwe60smQUDnd4Rz1ZAQZnFAGDd0hihh12CEE9kjAEVlycXIg7BAsMB6SlnJ87paqbSKiKoqusnbMdmDC2tXQlkUhziYtyWTxIfy6BE8WJt5YEvpJivxNaGmLHT0VnOgGYf0dZXS7APdpB309RnHOG5gDqXGLDaC457D1zZ/V/nmOM82XiHQjYKhKP1oZmADdEAAAh+QQFBQAAACwAAAAAGAAXAAAEchDISasKNeuJFKoHs4mUYlJIkmjIV54Soypsa0wmLSnqoTEtBw52mG0AjhYpBxioEqRNy8V0qFzNw+GGwlJ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0KqvKalTiYPhp1LBFTtp10Is6mT5gdVFx1bRN8FTsVCAqDOB9+KhEAIfkEBQUAAAAsAgASAB0ADgAABHgQyEmrBePS4bQdQZBdR5IcHmWEgUFQgWKaKbWwwSIhc4LonsXhBSCsQoOSScGQDJiWwOHQnAxWBIYJNXEoFCiEWDI9jCzESey7GwMM5doEwW4jJoypQQ743u1WcTV0CgFzbhJ5XClfHYd/EwZnHoYVDgiOfHKQNREAIfkEBQUAAAAsAAAPABkAEQAABGeQqUQruDjrW3vaYCZ5X2ie6EkcKaooTAsi7ytnTq046BBsNcTvItz4AotMwKZBIC6H6CVAJaCcT0CUBTgaTg5nTCu9GKiDEMPJg5YBBOpwlnVzLwtqyKnZagZWahoMB2M3GgsHSRsRACH5BAUFAAAALAEACAARABgAAARcMKR0gL34npkUyyCAcAmyhBijkGi2UW02VHFt33iu7yiDIDaD4/erEYGDlu/nuBAOJ9Dvc2EcDgFAYIuaXS3bbOh6MIC5IAP5Eh5fk2exC4tpgwZyiyFgvhEMBBEAIfkEBQUAAAAsAAACAA4AHQAABHMQyAnYoViSlFDGXBJ808Ep5KRwV8qEg+pRCOeoioKMwJK0Ekcu54h9AoghKgXIMZgAApQZcCCu2Ax2O6NUud2pmJcyHA4L0uDM/ljYDCnGfGakJQE5YH0wUBYBAUYfBIFkHwaBgxkDgX5lgXpHAXcpBIsRADs=',
            style: 'width: 15px; height: 15px; vertical-align: middle;'
        }
    },
    parame = {},
    prop = ''
    callback = {
        refresh: null,
        load: null
    };

    function createDom() {
        var defaultcss = 'height: 0; display: none; text-align: center; font-size: 12px; ';
        $('<div class="' + parame.refreshDom.prop.replace('.', '') + '" style="' + defaultcss + '">' + parame.refreshDom.startText + '</div>').insertBefore($(prop));
        $('<div class="' + parame.loadDom.prop.replace('.', '') + '" style="' + defaultcss + '">' + parame.loadDom.startText + '</div>').insertAfter($(prop));
    }

    var method = {
        refreshMove: function () {
            if (parame.isStartLoad) {
                console.log('已经在加载了,不能刷新');
                return;
            }
            console.log('刷新开始');
            parame.isStartRefresh = true;
            (parame.continueMoveDirection === 'top') && (parame.positionTop -= parame.topSpeed);
            (parame.continueMoveDirection === 'bottom') && (parame.positionTop += parame.topSpeed);

            $(prop).prev(parame.refreshDom.prop).fadeIn(parame.animateSpeed);
            $(prop).css({ 'position': 'relative' }).animate({ 'top': parame.positionTop }, 0);
            $(prop).prev(parame.refreshDom.prop)
                .text(parame.positionTop >= parame.whenThisHeightExecuteCallback
                ? parame.refreshDom.endText : parame.refreshDom.startText);
        },
        loadMove: function () {
            if (parame.isStartRefresh) {
                console.log('已经在刷新了,不能加载');
                return;
            }
            parame.isStartLoad = true;
            console.log('加载开始');
            (parame.continueMoveDirection === 'top') && (parame.positionBottom += parame.topSpeed);
            (parame.continueMoveDirection === 'bottom') && (parame.positionBottom -= parame.topSpeed);

            $(prop).next(parame.loadDom.prop).fadeIn(parame.animateSpeed);
            $(prop).css({ 'position': 'relative' }).animate({ 'bottom': parame.positionBottom }, 0);
            $(prop).next(parame.loadDom.prop)
                    .text(parame.positionBottom >= parame.whenThisHeightExecuteCallback
                    ? parame.loadDom.endText : parame.loadDom.startText);
        },
        closeRefresh: function () {
            parame.isStartRefresh = parame.isRefreshIng = false;
            parame.positionTop = 0;//重置偏移量
            parame.continueMoveDirection = '';
            parame.moveArray = new Array();
            $(prop).animate({ 'top': 0 }, parame.animateSpeed, function () {
                $(prop).removeAttr('style').prev(parame.refreshDom.prop).fadeOut(parame.animateSpeed);
                console.log('刷新结束');
            });
        },
        closeLoad: function () {
            parame.isStartLoad = parame.isLoadIng = false;
            parame.positionBottom = 0;//重置偏移量
            parame.continueMoveDirection = '';
            parame.moveArray = new Array();
            $(prop).animate({ 'bottom': 0 }, parame.animateSpeed, function () {
                $(prop).removeAttr('style').next(parame.loadDom.prop).fadeOut(parame.animateSpeed);
                console.log('加载结束');
            });
        },
        refreshIng: function () {
            console.log(parame.refreshDom.ingText);
            parame.isStartRefresh = parame.isRefreshIng = true;
            $(prop).prev(parame.refreshDom.prop)
                .html('<img src="' + parame.loadImg.src + '" style="' + parame.loadImg.style + '"/>' + parame.refreshDom.ingText);
            $(prop).css({ 'position': 'relative' }).animate({ 'top': parame.whenThisHeightExecuteCallback }, parame.animateSpeed);
            callback.refresh();
        },
        loadIng: function () {
            console.log(parame.loadDom.ingText);
            parame.isStartLoad = parame.isLoadIng = true;
            $(prop).next(parame.loadDom.prop)
                .html('<img src="' + parame.loadImg.src + '" style="' + parame.loadImg.style + '"/>' + parame.refreshDom.ingText);
            $(prop).css({ 'position': 'relative' }).animate({ 'bottom': parame.whenThisHeightExecuteCallback }, parame.animateSpeed);
            callback.load();
        },
        cancel: function () {
            console.log('滑动时受到了伤害');
            parame.isStartRefresh = parame.isStartLoad = parame.isRefreshIng = parame.isLoadIng = false;
            parame.positionTop = parame.positionBottom = 0;//重置偏移量
            parame.continueMoveDirection = '';
            parame.moveArray = new Array();
            $(prop).animate({ 'top': 0, 'bottom': 0 }, parame.animateSpeed, function () {
                $(prop).removeAttr('style');
                $(prop).prev(parame.refreshDom.prop).fadeOut(parame.animateSpeed);
                $(prop).next(parame.loadDom.prop).fadeOut(parame.animateSpeed);
            });
        },
        isRefreshBug: function () {
            return !parame.isRefreshIng
                && $(prop).prev(parame.refreshDom.prop).css('display') != 'none'
                && parame.positionTop < parame.whenThisHeightExecuteCallback;
        },
        isLoadBug: function () {
            return !parame.isLoadIng
                && $(prop).next(parame.loadDom.prop).css('display') != 'none'
                && parame.positionBottom < parame.whenThisHeightExecuteCallback;
        }
    };
    function event() {
        $(prop).unbind('touchstart touchmove touchend touchcancel')
        .on('touchstart', function (e) {
            console.log('开始滑动');
            parame.screenY = e.originalEvent.targetTouches[0].screenY;
        })
        .on('touchmove', function (e) {
            console.log('滑动中');
            if (parame.isRefreshIng || parame.isLoadIng) {
                console.log('已经在刷新/加载了,禁止滑动');
                return;
            }
            parame.positionY = window.scrollY;
            parame.moveArray.push(e.originalEvent.targetTouches[0].screenY);

            if (parame.moveArray.length > 1) {
                if (e.originalEvent.targetTouches[0].screenY > parame.moveArray[parame.moveArray.length - 2]) {//-2是因为本次移动的y轴数值位于该数组的最后一位
                    parame.continueMoveDirection = 'bottom';
                } else if (e.originalEvent.targetTouches[0].screenY < parame.moveArray[parame.moveArray.length - 2]) {
                    parame.continueMoveDirection = 'top';
                } else {
                    parame.continueMoveDirection = '';
                }
            } else {
                parame.continueMoveDirection = '';
            }

            console.log(parame.continueMoveDirection);
            if (parame.positionY === 0 && (($(document).height() - $(window).height()) == 0)) {//没有滚动条的时候
                //刷新
                console.log('刷新么么-无滚动条');
                (parame.isStartRefresh || parame.continueMoveDirection === 'bottom') && method.refreshMove();

                //加载
                console.log('加载么么-无滚动条');
                (parame.isStartLoad || parame.continueMoveDirection === 'top') && method.loadMove();
            } else {
                //刷新
                console.log('刷新么么-有滚动条');
                (parame.positionY === 0
                    && !parame.isStartLoad
                    && parame.continueMoveDirection === 'bottom')
                && method.refreshMove();

                //加载                
                console.log('加载么么-有滚动条');
                ((parame.positionY === ($(document).height() - $(window).height()))
                    && parame.continueMoveDirection === 'top'
                    && !parame.isStartRefresh)
                && method.loadMove();
            }
        })
        .on('touchend', function () {
            console.log('滑动结束');
            //刷新
            parame.positionTop >= parame.whenThisHeightExecuteCallback && method.refreshIng();
            //加载
            parame.positionBottom >= parame.whenThisHeightExecuteCallback && method.loadIng();

            //解决滑动距离小于刷新/加载距离未重置的bug
            method.isRefreshBug() && method.closeRefresh();
            method.isLoadBug() && method.closeLoad();
        })
        .on('touchcancel', function () {
            method.cancel();
        });
    }

    function init() {
        createDom();
        event();
    }

    window.noName = {
        /*
            config:{
                //主要参数
                prop:'',//dom元素
                refreshCallback:function(){},//刷新回调
                loadCallback:function(){}//加载回调
                //其他想自定义的参数请看defaultParame变量
            }
        */
        init: function (config) {
            prop = config.prop;
            if (typeof (config.prop) === 'undefined'
                || config.prop === ''
                || typeof (config.refreshCallback) != 'function'
                || typeof (config.loadCallback) != 'function')
                throw new Error('必需参数为空');
            callback.refresh = config.refreshCallback;
            callback.load = config.loadCallback;
            parame = $.extend({}, defaultParame, config.config || {});
            init();
        },
        //刷新完成后关闭
        closeRefresh: method.closeRefresh,
        //加载完成后关闭
        closeLoad: method.closeLoad
    };
}());

html:

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>index</title>
    <link href="~/Content/css/comm/reset.css" rel="stylesheet" />
    <style>
        #content {
            width: 100%;
            overflow: hidden;
        }
    </style>
</head>
<body>
    <div class="wrapper" id="wrapper">
        <div id="content"></div>
    </div>
    <script src="~/Content/js/comm/jquery.min.js"></script>
    <script src="~/Content/js/comm/noName.js"></script>
    <script>

        function fillData() {
            var content = '';
            for (var i = 0; i < 5; i++) {
                content += '<p>这里就是内容' + i + '</p>';
            }
            $('#content').append(content);
        }

        fillData();

        noName.init({
            prop: '',
            refreshCallback: function () {
                setTimeout(function () {
                    $('#content').html('');
                    fillData();
                    noName.closeRefresh();
                }, 3000)
            },
            loadCallback: function () {
                setTimeout(function () {
                    fillData();
                    noName.closeLoad();
                }, 3000)
            }
        });
    </script>
</body>
</html>
posted @ 2016-05-17 21:37  myEsn2E9  阅读(1929)  评论(0编辑  收藏  举报