dialog.js 11.5 KB
Newer Older
胡畅 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
/*
 * dialog
 * http://sufangyu.github.io
 * 1.0.3(2016-07-15)
 */
;(function(win,$){

    /*
     * Private methods
     */
    var wrap, overlay, content, title, close, cancelBtn, okBtn, delBtn, settings, timer, aTimer;

    var _renderDOM = function(){
        if( $('.dialog-wrap').length > 0){
            return;
        }

        clearTimeout(timer);
        clearTimeout(aTimer);
        settings.onBeforeShow();

        $('body').append( dialogWrapper = $('<div class="dialog-wrap '+ settings.dialogClass +'"></div>') );
        dialogWrapper.append(
            overlay = $('<div class="dialog-overlay"></div>'),
            content = $('<div class="dialog-content dialog-content-animate"></div>')
        );
        solveTapBug = $('<div class="solve-tap-bug" style="margin:0;padding:0;border:none;background:rgba(255,255,255,0.01); -webkit-tap-highlight-color:rgba(0,0,0,0); width:100%; height:100%; position:fixed; top:0px; left:0px;"></div>').insertBefore(dialogWrapper);


        switch (settings.type){
            case 'alert' :
                if(settings.showTitle){
                    content.append(
                        title = $('<div class="dialog-content-hd"><h4 class="dialog-content-title">'+ settings.titleText +'</h4></div>')
                    );
                }
                content.append(
                    contentBd = $('<div class="dialog-content-bd">'+ settings.contentHtml +'</div>')
                );
                content.append(
                    contentFt = $('<div class="dialog-content-ft"></div>')
                );
                contentFt.append(
                    okBtn = $('<button class="dialog-btn dialog-btn-ok '+ settings.buttonClass.ok +'" >'+ settings.buttonText.ok +'</button>')
                );
                break;

            case 'confirm' :
                if(settings.showTitle){
                    content.append(
                        title = $('<div class="dialog-content-hd"><h4 class="dialog-content-title">'+ settings.titleText +'</h4></div>')
                    );
                }
                content.append(
                    contentBd = $('<div class="dialog-content-bd">'+ settings.contentHtml +'</div>')
                );
                content.append(
                    contentFt = $('<div class="dialog-content-ft"></div>')
                );
                contentFt.append(
                    cancelBtn = $('<button class="dialog-btn dialog-btn-cancel '+ settings.buttonClass.cancel +'" >'+ settings.buttonText.cancel +'</button>'),
                    okBtn = $('<button class="dialog-btn dialog-btn-ok '+ settings.buttonClass.ok +'" >'+ settings.buttonText.ok +'</button>')
                );
                break;

            case 'info' :
                var infoContent = settings.contentHtml || '<img class="info-icon" src="'+ settings.infoIcon +'" alt="'+ settings.infoText +'" /><p class="info-text">'+ settings.infoText +'</p>';
                content.append(
                    contentBd = $('<div class="dialog-content-bd">'+ infoContent +'</div>')
                );
                dialogWrapper.addClass('dialog-wrap-info');
                content.addClass('dialog-content-info').removeClass('dialog-content-animate');
                break;

            case 'tips' :
                var tipsContent = settings.contentHtml || (settings.infoIcon ? '<img class="info-icon" src="'+ settings.infoIcon +'" alt="'+ settings.infoText +'" />' : '') + '<span class="info-text">'+ settings.infoText +'</span>';
                content.append(
                    contentBd = $('<div class="dialog-content-bd">'+ tipsContent +'</div>')
                );
                dialogWrapper.addClass('dialog-wrap-tips');
                content.addClass('dialog-content-tips').removeClass('dialog-content-animate');
                break;
        }

        setTimeout(function(){
            dialogWrapper.addClass('dialog-wrap-show');
            settings.onShow();
            _resize();
        }, 20);

        _setDirectionAndAlign();

        // 解决zepto无法正常获取实际高度造成限制最大高度失效
        setTimeout(function(){
            _setMaxHeight();
            _setDirectionAndAlign();
        }, 100);

    };

    var _setDirectionAndAlign = function(){
      $(contentBd).css({'direction': settings.direction,'text-align': settings.align});
    }

    var _bindEvent = function() {

        touchEvent.tap($(okBtn), function(){
            settings.onClickOk();
            $.dialog.close();
            return false;
        });

        touchEvent.tap($(cancelBtn), function(){
            settings.onClickCancel();
            $.dialog.close();
            return false;
        });

        // overlay clisk hide
        if( settings.overlayClose ){
            touchEvent.tap($(overlay), function(){
                $.dialog.close();
            });
        }

        // auto close, set autoClose and type isn't info
        if( settings.autoClose > 0 ){
            _autoClose();
        }

        // stop body scroll
        $(document).on('touchmove', function(event){
            if( $(dialogWrapper).find($(event.target)).length ){
                return false;
            }else{
                return true;
            }
        });
        _touchScroll();

    };

    var _autoClose = function(){
        clearTimeout(aTimer);
        aTimer = window.setTimeout(function(){
            $.dialog.close();
        }, settings.autoClose);
    };

    var _setMaxHeight = function(){
        var windowHeight = $(window).height();

        $(contentBd).removeAttr('style');
        if( $(content).height() >= windowHeight - 10 ){
            var contentTitleHeight = $(title).height() + parseInt($(title).css('margin-top')) + parseInt($(title).css('margin-bottom')) + parseInt($(title).css('padding-top')) + parseInt($(title).css('padding-bottom'));
            var contentFtHeight = $(contentFt).height() + parseInt($(contentFt).css('margin-top')) + parseInt($(contentFt).css('margin-bottom')) + parseInt($(contentFt).css('padding-top')) + parseInt($(contentFt).css('padding-bottom'));
            var contentBdSpace =  parseInt($(contentBd).css('margin-top')) + parseInt($(contentBd).css('margin-bottom')) + parseInt($(contentBd).css('padding-top')) + parseInt($(contentBd).css('padding-bottom'));

            var contentMaxHeight = windowHeight - contentTitleHeight - contentFtHeight - contentBdSpace - 50;
            $(contentBd).css({'max-height': contentMaxHeight, 'overflow-y':'auto'});
        }
    };

    var _resize = function(){

        $(window).on('resize', function(){
            clearTimeout(rTimer);
            var rTimer = window.setTimeout(function(){
                _setMaxHeight();
            },100);
        });
    };

    var _touchScroll = function(){
        var position = {
            x: 0,
            y: 0,
            top: 0,
            left: 0
        };

        // 滚动条top位置 = 原来的滚动条top - 滚动的距离
        $(contentBd).on("touchstart", function(e) {
            position.x = event.changedTouches[0].clientX,
            position.y = event.changedTouches[0].clientY,
            position.top == 0 && (position.top = $(this).scrollTop()),
            position.left == 0 && (position.left = $(this).scrollLeft())
        }).on("touchmove", function(e) {
            $(this).scrollTop(position.top - event.changedTouches[0].clientY + position.y),
            $(this).scrollLeft(position.left - event.changedTouches[0].clientX + position.x)
        }).on("touchend", function(e) {
            if (position.x != 0 || position.y != 0) {
                // return (event.changedTouches[0].clientY - position.y > 20 || event.changedTouches[0].clientX - position.x > 20) && (e = !1),
                position = {
                    x: 0,
                    y: 0,
                    top: 0,
                    left: 0
                }
            }
            e.preventDefault();
        })
    };

    var touchEvent = {
        tap : function(element, fn){
            if ('ontouchstart' in window || 'ontouchstart' in document) {
                var supportsTouch = true;
            } else if(window.navigator.msPointerEnabled) {
                var supportsTouch = true;
            }

            if(supportsTouch){
                var startTx, startTy;
                element.on('touchstart',function(e){
                    var touches = e.touches ? e.touches[0] : e.originalEvent.touches[0];
                    startTx = touches.clientX;
                    startTy = touches.clientY;
                });

                element.on('touchend',function(e){
                    var touches = e.changedTouches ? e.changedTouches[0] : e.originalEvent.changedTouches[0];
                    endTx = touches.clientX,
                    endTy = touches.clientY;
                    // 在部分设备上 touch 事件比较灵敏,导致按下和松开手指时的事件坐标会出现一点点变化
                    if( Math.abs(startTx - endTx) < 6 && Math.abs(startTy - endTy) < 6 ){
                        fn();
                    }
                    e.preventDefault();
                });
            }else{
                element.on('click',function(e){
                    fn();
                });
            }
        }
    };



    /*
     * Public methods
     */

    $.dialog = function(options) {
        settings = $.extend({}, $.fn.dialog.defaults, options);
        $.dialog.init();
        return this;
    };

    $.dialog.init = function(){
        _renderDOM();
        _bindEvent();
    };


txy committed
257
    $.dialog.close = function(callback){
胡畅 committed
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
        settings.onBeforeClosed();

        dialogWrapper.removeClass('dialog-wrap-show');
        timer = setTimeout(function(){
            dialogWrapper.remove();
            settings.onClosed();
        }, 100);

        // cancel stop body scroll
        $(document).on('touchmove', function(event){
            return true;
        });

        // 解决touchend点透,延迟阻止点透层隐藏
        setTimeout(function(){
            solveTapBug.remove();
txy committed
274
            callback && callback();
胡畅 committed
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
        }, 350);
    };

    $.dialog.update = function(params) {
        if(params.infoText) {
            content.find('.info-text').html(params.infoText);
        }
        if(params.infoIcon) {
            content.find('.info-icon').attr('src', params.infoIcon);
        }
        if(params.autoClose>0){
            window.setTimeout(function(){
				if(params.onBeforeClosed) { params.onBeforeClosed(); }
                $.dialog.close();
                if(params.onClosed) { params.onClosed(); }
            }, params.autoClose);
        }
    };


    // 插件
    $.fn.dialog = function(options){
        return this;
    };


    $.fn.dialog.defaults = {
        type : 'alert',     // alert、confirm、info、tips
        titleText : '信息提示',
        showTitle : true,
        contentHtml : '',
        dialogClass : '',
        autoClose : 0,
        overlayClose : false,
        drag : false,
        direction: 'ltr',
        align: 'left',

        buttonText : {
            ok : '确定',
            cancel : '取消',
            delete : '删除'
        },
        buttonClass : {
            ok : '',
            cancel : '',
            delete : ''
        },

        infoText : '',      // working in info type
        infoIcon : '',      // working in info type

        onClickOk : function(){},
        onClickCancel : function(){},
        onClickClose : function(){},

        onBeforeShow : function(){},
        onShow : function(){},
        onBeforeClosed : function(){},
        onClosed : function(){}
    }

})(window, window.Zepto || window.jQuery);