简单实现移动端弹窗及loading组件

最近用到了很多弹窗和页面加载效果,之前只是随调随用,也没去整理,网上大多的插件要不是太冗余,就是样式风格太呆板,所以今天闲着就整理了一个出来。具备基本的弹窗功能,包括alertconrirmtips三种。(三种的区别是alert弹窗只生成确定按钮,接受确定回调。confirm弹窗生成确定和取消按钮,接受确定和取消回调。tips不生成按钮,可以设置自动隐藏或者点击遮罩层来隐藏)。组件可以更换背景文字宽高等属性,也具备选择是否添加遮罩层回调函数等基本功能。此外,也一并引入了页面loading的效果。

组件用到了css3的动画库** animated.min.css,可以自行引入。弹窗组件主要用闭包的形式去写,支持将整个变量赋值给window,也支持用es6 module exports** 的方法供项目随处使用。下面贴上popupwin.js的代码:

!function(){
    var popup = { //css3动画库所有动画效果 任君使用
        EFFECT:["bounce","flash","pulse","rubberBand","shake","swing","tada","wobble","bounceIn","bounceInDown","bounceInLeft","bounceInRight","bounceInUp","bounceOut","bounceOutDown","bounceOutLeft","bounceOutRight","bounceOutUp","fadeIn","fadeInDown","fadeInDownBig","fadeInLeft","fadeInLeftBig","fadeInRight",
"fadeInRightBig","fadeInUp","fadeInUpBig","fadeOut","fadeOutDown","fadeOutDownBig","fadeOutLeft","fadeOutLeftBig","fadeOutRight","fadeOutRightBig","fadeOutUp","fadeOutUpBig","flip","flipInX","flipInY","flipOutX","flipOutY","lightSpeedIn","lightSpeedOut","rotateIn","rotateInDownLeft","rotateInDownRight",
"rotateInUpLeft","rotateInUpRight","rotateOut","rotateOutDownLeft","rotateOutDownRight","rotateOutUpLe",
"rotateOutUpRigt","slideInDown","slideInLeft","slideInRight","slideOutLeft","slideOutRight","slideOutUp","hinge","rollIn","rollOut"],

        defaultOptions:{
            themeColor: {
                bgColor: '#e5004f', //主题背景颜色
                fontColor: '#fff' //主题文字颜色
            },  
            type: 'alert',  //弹框类型 包括 alert、confirm、tips三种
            title: '提示',    //弹框标题
            content: '', //弹框内容
            width: '90%', //弹框宽度
            yes: '确定', //确定按钮 文本
            no: '取消', //取消按钮 文本
            isHide: false, //是否在弹出后隐藏
            onConfirm: function(){ //点击确定执行的回调函数
                var options = {};
                options.effect = 'bounceOut';
                this.showAnimation('bounceOut',true);
                this.removeMask();
            }, 
            onCancel: function(){ //点击取消执行的回调函数
                var options = {};
                options.effect = 'bounceOut';
                this.showAnimation('bounceOut',true);
                this.removeMask();
            }, 
            effect: 'bounceIn', //弹框效果
            mask: null //是否有背景遮罩层 传入透明度和是否可以点击  如{opacity: 0.8,isClick: true}
        },
        _bindEvent: function(options){
            if(options.onConfirm){
                $(document).off('click','.confirm-btn');
                $(document).on('click','.confirm-btn',options.onConfirm.bind(this));
            }
            if(options.onCancel){
                $(document).off('click','.cancel-btn');
                $(document).on('click','.cancel-btn',options.onCancel.bind(this));
            }
        },
        showAnimation: function(effect,isHide){
            //isHide参数表示弹窗在弹出后隔一段时间自动隐藏
            if(effect && this.checkEffect(effect)){
                $('.dialog-diy').addClass(' animated '+ effect).one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend',function(){
                    $(this).removeClass(' animated '+ effect);
                    if(isHide){
                        $('.dialog-diy').hide();
                    }
                });
            }
        },
        getTemplate: function(options){
            var onConfirm = (options.onConfirm && typeof(options.onConfirm) === 'function' ?'onConfirm' : '');
            var onCancel = (options.onConfirm && typeof(options.onCancel) === 'function' ?'onCancel' : '');
            switch(options.type){
                case 'alert': return $('<div class="popup dialog-diy" style="width:'+options.width+';left:'+getOffsetLeft(options.width)+'%">\
                                <span class="close"></span>\
                                <div class="pop-header" style="background:'+options.themeColor.bgColor+';color:'+options.themeColor.fontColor+'">'+options.title+'</div>\
                                <div class="pop-body">'+options.content+'\
                                </div>\
                                <div class="pop-footer"><a class="confirm-btn '+onConfirm+'" >'+options.yes+'</a></div>\
                                </div>');
                case 'confirm': return $('<div class="popup dialog-diy" style="width:'+options.width+';left:'+getOffsetLeft(options.width)+'%">\
                                <span class="close"></span>\
                                <div class="pop-header" style="background:'+options.themeColor.bgColor+';color:'+options.themeColor.fontColor+'">'+options.title+'</div>\
                                <div class="pop-body">'+options.content+'\
                                </div>\
                                <div class="pop-footer"><a class="cancel-btn '+onCancel+'" href="javascript:void(0)">'+options.no+'</a>\
                                <a class="confirm-btn '+onConfirm+'" href="javascript:void(0)">'+options.yes+'</a>\
                                </div>\
                                </div>');
                case 'tips': return $('<div class="popup dialog-diy" style="width:'+options.width+';left:'+getOffsetLeft(options.width)+'%">\
                                <span class="close"></span>\
                                <div class="pop-header" style="background:'+options.themeColor.bgColor+';color:'+options.themeColor.fontColor+'">'+options.title+'</div>\
                                <div class="pop-body">'+options.content+'\
                                </div>\
                                </div>') ;

            }
            function getOffsetLeft(width){
                var leftRate = 0;
                var widthRate = Number(width.substring(0,width.length-1));
                if(widthRate > 0 && widthRate < 100) {
                    leftRate = (100-widthRate)/2;
                } 
                return leftRate;
            }
        },
        removeDialog: function(){
            if($('.dialog-diy').length){
                $('.dialog-diy').remove();
            }
            if($('#popupMask').length){
                $('#popupMask').remove();
            }
        },
        removeMask: function(){
            if($('#popupMask').length){
                $('#popupMask').fadeOut();
                setTimeout(function(){
                    $('#popupMask').remove();
                },1000);
            }
        },
        checkEffect: function(effect){
            effect = effect || "";
            if(!effect){return false;}
            var tmp = this.EFFECT.join(",");
            if(tmp.indexOf(effect)>=0){return true;}
            return false;
        },
        setMask: function(mask){
            //传入两个参数 透明度和是否可以点击 isClick为真的情況下可以通過点击遮罩层关闭弹窗
            var self = this;
            var $mask = $('<div id="popupMask" style="width:100%;height:100%;position:absolute;left:0;top:0;background:#000;opacity:'+mask.opacity+'"></div>');
            $('body').append($mask);
            if(mask.isClick){
                $(document).off('click','#popupMask');
                $(document).on('click','#popupMask',function(){
                    self.showAnimation('bounceOut',true);
                    self.removeMask();
                });
            }
        },
        isDot: function(num){ //判断是否为大于0小于1的小数
            if(!isNaN(num) && num < 1){
                return true;
            }
            return false;
        },
        alert: function(title,content,cb){ 
            var opts = this.defaultOptions;
            opts.title = title || this.defaultOptions.title;
            opts.content = content;
            opts.type = 'alert';
            if(cb && typeof cb === 'function'){
                opts.onConfirm = cb;
            }
            var tpl = this.getTemplate(opts);
            $('body').append(tpl);
            this.showAnimation(opts.effect);
            this._bindEvent(opts);
        },
        confirm: function(title,content,cb1,cb2){
            var opts = this.defaultOptions;
            opts.title = title || this.defaultOptions.title;
            opts.content = content;
            opts.type = 'confirm';
            if(cb1 && cb1 === 'function'){
                opts.onConfirm = cb1;
            }
            if(cb2 && cb2 === 'function'){
                opts.onCancel = cb2;
            }
            var tpl = this.getTemplate(opts);
            $('body').append(tpl);
            this.showAnimation(opts.effect);
            this._bindEvent(opts);
        },
        tips: function(title,content){
            var self = this;
            var opts = this.defaultOptions;
            opts.title = title || this.defaultOptions.title;
            opts.content = content || '';
            opts.type = 'tips';
            var tpl = this.getTemplate(opts);
            $('body').append(tpl);
            this.showAnimation(opts.effect);
            setTimeout(function(){
                self.showAnimation('bounceOut',true);
                self.removeMask();
            },3000);
        },
        removeLoading: function(){
            if($('.popup-spinner').length){
                $('.popup-spinner').fadeOut();
                setTimeout(function(){
                    $('.popup-spinner').remove();
                },2000);
            }
            if($('#popupMask').length){
                $('#popupMask').fadeOut();
                setTimeout(function(){
                    $('#popupMask').remove();
                },2000);
            }
        },
        loading: function(opacity,isClick,color){//传入透明度,是否可以点击,加载条颜色
            if($('.popup-spinner').length){
                $('.popup-spinner').remove();
            }
            if($('#popupMask').length){
                $('#popupMask').remove();
            }
            var $loading = $('<div class="popup-spinner"><div style="background-color:'+color+'" class="bounce1"></div><div style="background-color:'+color+'" class="bounce2"></div><div style="background-color:'+color+'" class="bounce3"></div></div>');
            $('body').append($loading);
            var mask = {opacity:opacity,isClick:isClick};
            this.setMask(mask);
        },
        _ready: function(options){
            console.log(options);
            var self = this;
            this.removeDialog();
            var tpl = this.getTemplate(options);
            $('body').append(tpl);
            if(options.mask && this.isDot(options.mask.opacity)){
                this.setMask(options.mask);
            }
            this.showAnimation(options.effect);
            if(options.isHide){
                setTimeout(function(){
                    self.showAnimation('bounceOut',true);
                    self.removeMask();
                },3000);
                
            }
        },
        _init: function(options){
            var options = options || this.defaultOptions;
            var self = this;
            for(var key in this.defaultOptions){
                if(options[key] == undefined){
                    options[key] = this.defaultOptions[key];
                }
            }
            $(function(){
                self._ready(options);
            });
            this._bindEvent(options);
        }
    };

    window.popup = popup; //赋值给window下的变量
    module.exports = popup; //es6模块导出
}();

可以通过 _init 函数初始化弹窗,也可以简洁调用alertconfirmtips。代码如下:

//导入相关 js css
import '../../common/css/popupwin.css'
import '../../common/css/animated.css'
import $ from 'expose-loader?!jquery'
import popup from '../../common/js/lib/popupwin.js'

//没有传递的参数将会使用组件的默认参数,参看defaultOptions
var options = {
    themeColor: {
        bgColor: 'yellow',
        fontColor: '#000'
    }, 
    type: 'confirm',  
    title: '温馨提示',  
    content: 'hellowrod!!!', 
    width: '90%', 
    yes: '确定',
    no: '取消', 
    isHide: false, 
        onConfirm: function(){alert('just do it');},
    onCancel: null, 
    effect: 'bounceIn',
    mask: {
          opacity: 0.8,
          isClick: true
        }
};

popup._init(options); //通用方式调用

//alert简洁调用
popup.alert('提示','helloworld come from alert'); 

//confirm简洁调用
popup.confirm('提示','helloworld come from confirm',function(){
   alert('just do it'); 
});

//tips简洁调用
popup.tips('提示','helloworld come from tips');

//loading加载
popup.loading(0.8,true,'#fff');

//移除loading
popup.removeLoading();


附上popupwin.css的样式代码

/**弹窗样式*/
.popup{width: 90%;max-width: 500px;margin: 30px auto 0 auto;position: absolute;background: #fff;border-radius: .1rem;top: 20%;left: 5%;z-index: 999;}
.popup .pop-header{color:#fff;padding:.08rem 0;background:#e5004f;text-align:center;font-size:.16rem;border-radius:.1rem .1rem 0 0;}
.popup .pop-body{padding:.15rem .15rem .15rem;min-height:1rem;color:#000;font-size:.16rem;}
.popup .pop-body.large{padding:.15rem;min-height:1rem;max-height:3rem;overflow:auto;}
.popup .pop-footer{text-align:center;padding-bottom:.2rem}
.popup .pop-footer .btn{width:60%;}


/**loading动画样式**/
.popup-spinner {width: 1rem;height: .3rem;position: absolute;top:50%;left:50%;margin-left: -.5rem;margin-top: -.15rem;line-height: .3rem;z-index: 1000;}
 
.popup-spinner > div {width: .15rem;height: .15rem;background-color: #67CF22;margin-left: .05rem;margin-right: .05rem;border-radius: 100%;display: inline-block;-webkit-animation: bouncedelay 1.4s infinite ease-in-out;animation: bouncedelay 1.4s infinite ease-in-out;-webkit-animation-fill-mode: both;animation-fill-mode: both;}
 
.popup-spinner .bounce1 {-webkit-animation-delay: -0.32s;animation-delay: -0.32s;}
 
.popup-spinner .bounce2 {-webkit-animation-delay: -0.16s;animation-delay: -0.16s;}
 
@-webkit-keyframes bouncedelay {0%, 80%, 100% { -webkit-transform: scale(0.0) }40% { -webkit-transform: scale(1.0) }}
 
@keyframes bouncedelay {0%, 80%, 100% {transform: scale(0.0);-webkit-transform: scale(0.0);} 40% {transform: scale(1.0);-webkit-transform: scale(1.0);}}

总结

无。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,569评论 25 707
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,618评论 4 59
  • 移动端dialog组件 dialogView是满足移动端下,用户自定义的dialog组件,API可扩展性强,使用便...
    小兴nice阅读 3,978评论 2 11
  • 调试android设备时输入adb devices出现提示error,经过一番折腾后终于解决了,首先重启设备,再在...
    雪花晒干阅读 740评论 0 1
  • 小夭说什么样的铠甲也没有用,内里还不是一碰就碎。大实话是这个世界上最没有营养的补品。撇嘴。 男人和女人生下来的时候...
    愚蠢的狐狸大叔阅读 252评论 2 0