zoukankan      html  css  js  c++  java
  • 自己封装一个弹框插件

    弹出层提示信息,这是移动前端开发中最常见的需求,你可能会想到一些流行的弹框插件,比如 经典的artDialog 炫酷的Sweetalert等等..

    但是慢慢地你其实会发现通常情况下需求定制化要求较高,一般的弹框插件可能只满足大部分要求,自定义花的时间还不如手动自己封装一个符合自己开发习惯的弹框组件,这样后续开发效率将大大提高。

    首先整理一下思路,原生javascript其实是有实现alert()方法的,但是那个会暂时性中断程序运行,并且足以让你丑拒!那么抛开这些细细一想,其实弹框就是两个div层,一个浮在底下的蒙层(遮罩层),将所有的元素遮起来,并且最好是半透明。另一个就是弹框主体部分了,一般情况需要水平垂直居中,并且通常包含标题,主体内容需要可定制,如果是模态框通常还有确认/取消按钮。最后就是弹出、关闭的时候一些动效。

     所以说完全可以自己封装一个,然后放在项目中公共js中去。能自己手写的尽量不用插件....

    一些默认属性值

    通过一个foreach循环,类似于传入的opts继承了defaultOpts属性,在调用弹框之前执行的before()方法,相当于一些准备工作

    var defaultOpts = {
                    title: '',//标题
                    content: '',//内容  文字 || html
                    height: 50,//默认屏幕(父级)的50%
                     80,//默认屏幕(父级)的80%
                    type: 'alert-default',//弹框类型
                    effect: 'fadeIn',//出现效果,默认下跌落
                    delayTime: 500,//效果延时时间,默认.5s
                    autoClose: false,//自动关闭
                    autoTime: 2000, //自动关闭时间默认2s
                    autoEffect: 'default',//关闭效果
                    ok: '确定',
                    okCallback: function(){},//确定回调
                    cancel: '取消',
                    cancelCallback: function(){},//取消回调
                    before : function() {
                        console.log('before')
                    }, 
                    close: function() {
                        console.log('close')
                    },
                    blankclose: false//空白处点击关闭
                }
    
            for (i in defaultOpts) {
                if (opts[i] === undefined) {
                    opts[i] = defaultOpts[i]
                }
            }
      
      opts.before && opts.before()

    dom结构

    定义一个数组对象,里面放弹框的dom元素,alert-mask为全屏的遮罩层,alert-content为弹框的主要内容区,最后通过.join(‘’)函数将数组转换为html ,再用jquery的append()方法追加在body节点最后。

    var alertHtml = [
                    '<section class="alert-main" id="alertMain">',
                        '<div class="alert-mask li-opacity" id="alertMask"></div>',
                        '<div class="alert-content '+ opts.type +'" id="alertContent">',
                        opts.content +'</div>',
                    '</section>'
                ]
    
            $('body').append(alertHtml.join(''))

    设置高宽了,水平垂直居中

    我这里是采用fixed定位,然后height是传进来的高(百分比),top距离屏幕顶端距离百分比为 100-传进来的高 /2 ,这样就实现了垂直居中,同理宽度也一样。这种水平垂直居中的办法也是自己长期实践总结出来自己认为最简单最实用的,兼容各种屏幕大小,当然还有很多方法,可以自行尝试

    var $alertContent = $('#alertContent'),
                $alertMain = $('#alertMain');
    
            $alertContent.css({
                'height': opts.height + '%',
                'top': (100 - opts.height)/2 + '%',
                'width': opts.width + '%',
                'left': (100 - opts.width)/2 + '%'
            })
    
            $('.li-opacity').css({
                '-webkit-animation-duration' : opts.delayTime/1000 + 's'
            })

    最后一句是给遮罩层赋一个动画执行时间,实现淡入效果。详情见下面的CSS @-webkit-keyframes opacity

    弹框效果

    我这里实现了四个效果,分别是fadeIn跌落,sideLeft从左侧飞入,scale放大,info提示信息。可以看到,我是定义了一个集合对象,分别放置了对应的css属性,然后通过两个setTimeout函数统一赋值

    var effect = {
                'fadeIn': 'top',
                'fadeInStart': '-100%',
                'fadeInValue': (100 - opts.height)/2 + '%',
                'sideLeft': 'left',
                'sideLeftStart': '-100%',
                'sideLeftValue': (100 - opts.width)/2 + '%',
                'scale': '-webkit-transform',
                'scaleStart': 'scale(0)',
                'scaleValue': 'scale(1)',
                'info': '-webkit-transform',
                'infoStart': 'scale(1.2)',
                'infoValue': 'scale(1)'
            }
    
            setTimeout(function(){
                $alertContent.css(effect[opts.effect],effect[opts.effect + 'Start']).addClass('alert-show')
    
                setTimeout(function(){
                    $alertContent.css(effect[opts.effect], effect[opts.effect + 'Value'])
                    opts.close && opts.close()
                },10)
            },opts.delayTime)

     

    空白处点击关闭

    通常情况下的需求,都会是要点击弹框空白处关闭弹框,一个点击事件搞定,重点是前面的选择器,jquery给了我们太多方便.... 当然最后为了防止点击到页面其他元素,阻止事件冒泡,组件默认行为..

    if(opts.blankclose) {
                $('.alert-main :not(.alert-content)').on('click',function(event){
                    $alertMain.remove()
                    opts.close && opts.close()
                    event.stopPropagation()
                    event.preventDefault()
                })
            }

    自动关闭

    当autoClose为true,并且autoTime大于零时,用一个延时事件自动关闭弹框

    if(opts.autoClose && opts.autoTime > 0) {
                setTimeout(function(){$alertMain.remove()},opts.autoTime)
                opts.close && opts.close()
            }

    演示:

    css

    @-webkit-keyframes opacity {
                0% {
                    opacity: 0; /*初始状态 透明度为0*/
                }
                50% {
                    opacity: 0; /*中间状态 透明度为0*/
                }
                100% {
                    opacity: 1; /*结尾状态 透明度为1*/
                }
            }
    
            .li-opacity {
                -webkit-animation-name: opacity; /*动画名称*/
                -webkit-animation-iteration-count: 1; /*动画次数*/
                -webkit-animation-delay: 0s; /*延迟时间*/
            }
            .alert-mask {
                position: fixed;
                height: 100%;
                width: 100%;
                left: 0%;
                top: 0%;
                z-index: 9998;
                background-color: rgba(0,0,0,.7);
            }
            .alert-content {
                position: fixed;
                box-sizing: border-box;
                border-radius: 4px;
                z-index: 9999;
                -webkit-transition: .4s;
                -moz-transition: .4s;
                transition: .4s;
                display: none;
            }
            .alert-show {
                display: block;
            }
            .alert-default {
                background-color: white;
            }

    html

    <p class="alert" data-flag="fadeIn">fadeIn</p>
       <p class="alert" data-flag="sideLeft">sideLeft</p>
       <p class="alert" data-flag="scale">scale</p>
       <p class="alert" data-flag="info">info</p>

    js

    require.config({
        jquery:'component/jquery/jquery-3.1.0.min',
        liAlert: 'li/li-alert',//常用弹框组件
    })
    
    require(['jquery'],function($){
            require(['liAlert'],function(){
                $('.alert').on('click',function(event){
                    $.alert({
                        content: '<h1 style="display:flex;justify-content:center;">我是弹框</h1>',
                        effect: $(event.currentTarget).attr('data-flag'),
                        blankclose: true,
                        //autoClose: true
                    })
                })
            })
        })

    效果图

    完整的代码已上传github: https://github.com/helijun/component/tree/master/alert

  • 相关阅读:
    MSDN Magazine搞错了
    Visual Studio 2005中设置调试符号(Debug Symbols)
    BCB 6的问题
    吴裕雄天生自然Spring Boot使用Spring Data JPA实现人与身份证的一对一关系映射
    吴裕雄天生自然Spring BootSpring Data JPA
    吴裕雄天生自然Spring BootSpring Boot对JSP的支持
    吴裕雄天生自然Spring BootSpring Boot的异常统一处理
    吴裕雄天生自然Spring Boot使用Spring Data JPA实现Author与Article的一对多关系映射
    吴裕雄天生自然Spring Boot解决 Error creating bean with name 'entityManagerFactory' defined in class path resource
    吴裕雄天生自然Spring Boot@ExceptionHandler注解和@ControllerAdvice注解
  • 原文地址:https://www.cnblogs.com/liliangel/p/6180212.html
Copyright © 2011-2022 走看看