1. 程式人生 > 其它 >js外掛封裝方法(一)

js外掛封裝方法(一)

技術標籤:前端開發jsjqueryhtml

也是從前輩那裡學來的封裝方法,比較好用,以下是封裝的提示框小外掛(顯示幾秒後自動消失)

/**
 * 提示框元件
 * created by lixn
 * 2019/10/31
 */

tipsPop = (function(){

    var obj = function (options){
        //處理引數
        this._setPara(options);	
        // 入口函式
        this.init();
    };
    obj.prototype = {
        //修正指標
        constructor: obj,

        //設定引數
        _setPara: function (option){
            this.el = document.querySelector(option.el) || 'body';//節點物件 //必傳引數 css選擇器
            this.creatId = 'tips'+ (new Date()).getTime();
            this.left = option.left || null;
            this.top = option.top || null;
            this.text = option.text || '操作成功!';  //提示語
            this.color = option.color || '#47c7ea';  //主題顏色
            this.time = option.time || '1000';  //延遲關閉得時間
            //回撥函式
            this.callback = option.callback || this.callback;
        },
        // 生成Dom元素
        _creatDom: function(){
            var self = this;
            this.creatDom = '<div id="'+this.creatId+'_pop" class="pop"></div><div id='+this.creatId+' class="tips-pop" style="left:'+this.left+';top:'+this.top+'">\
            <div class="tips-head" style="background-color:'+this.color+'">提示<span id="tips_close" class="tips-close">&times;</span></div>\
            <div class="tips-body">'+this.text+'</div>\
            </div>';

            $(this.el).append(this.creatDom);
            // 點選關閉
            $('#tips_close').click(function(){
                self._removeDom();
            })
        },
        _removeDom: function(){
            var self = this;
            $('#'+self.creatId).slideUp();
            $('#'+self.creatId+'_pop').remove();
            setTimeout(function(){
                $('#'+self.creatId).remove();
            },300)
        },
        callback: function(){
           
        },
        //入口函式
        init: function (){
            var self = this;
            // 建立節點
            this._creatDom();
            // 關閉彈窗
            setTimeout(function(){
                self._removeDom();
            },this.time)
            
        }
    };
    return obj;
})();

使用方法:

var tips = new tipsPop({text: '新增成功!'});