jQuery弹簧插件编写基础之“又见弹窗”

2020-05-29 07:21:05易采站长站整理

width: this.opts.width,
height: this.opts.height,
position: 'absolute',
top: '30%',
left: '50%',
marginLeft: '-' + (this.opts.width.split('px')[0] / 2) + 'px'
}).attr('class',this.opts.winCssName).on('click', function(event) {
event.stopPropagation();
});
titleAreaDom = popWinDom.find('div:eq(0)')
.text(this.opts.title)
.attr('class',this.opts.titleCssName);
descAreaDom = popWinDom.find('div:eq(1)')
.text(this.opts.desc)
.attr('class',this.opts.descCssName);
btnAreaDom = popWinDom.find('div:eq(2)')
.attr('class',this.opts.btnAreaCssName);
this.opts.btnArr.map(function(item, index) {
btnAreaDom.append($('<button></button>')
.text(item)
.attr({'data-index':index, 'class':_this.opts.btnCssName})
.on('click', function() {
_this.opts.callback($(this).attr('data-index'));
$.fn.popWin.hide(_this.$ele);
}));
});
this.$ele.append(popWinDom);
$.fn.popWin.show(this.$ele);
}
}
$.fn.popWin = function(options) {
var superType = new SubType(this, options);
superType.createPopWin();
return this;
}
$.fn.popWin.show = function($ele) {
$ele.show();
}
$.fn.popWin.hide = function($ele) {
$ele.hide();
}
$.fn.popWin.defaults = {
width: '600',
height: '250',
title: 'title',
desc: 'description',
winCssName: 'pop-win',
titleCssName: 'pop-title',
descCssName: 'pop-desc',
btnAreaCssName: 'pop-btn-box',
btnCssName: 'pop-btn',
btnArr: ['确定'],
callback: function(){}
}
})(jQuery);

如上,一个完整的弹窗插件就在这里了。

说下这个标红的 return this 是干什么用的,前面已说过 this 在这里是被选中的jQuery对象。将其return就可以在调用完我们的插件方法后可以继续调用jQ对象上的其他方法,也就是jQuery的链式操作,说玄乎点就叫级联函数。

OK!趁热打铁,我们来看看暴露出去的两个方法重写之后效果怎么样,毕竟对插件暴露部分的扩展和重写是很牛逼的一块东西。

想象个情景,你用了这个插件后觉得简单的show和hide效果简直是low爆了,决定重写这个弹出和隐藏的效果:


$.fn.popWin.show = function($ele) {
  $ele.children().first().css('top','-30%').animate({top:'30%'},500);
  $ele.show();
}
$.fn.popWin.hide = function($ele) {
  $ele.children().first().animate({top:'-30%'},500,function() {
    $ele.hide();
  });
}

你在自己的代码里加上上面两段,然后发现弹窗有了一个简单的上下滑动进入屏幕的效果,同时又不会影响我们弹窗的创建,证明我们的暴露方法还算合理。