利用原型和原型链实现的封装方法,比较好用,以下是封装的提示框小插件(显示几秒后自动消失)
/**
* 提示框组件
* 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">×</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: '新增成功!'});