在编写程序方面,使用插件会让人感觉轻松的多,接下来是制作手风琴插件的案例
$.fn.accordion = function (colors, width) {
// 如果用户没有传参数, 设置默认值
colors = colors || [];
width = width || 20;
//让当前的对象去找li
var $li = this.find("li");
//渲染颜色
$li.each(function (index, ele) {
$(ele).css("backgroundColor", colors[index]);
})
//获取当前显示800的那个宽度 = 总宽度 - width*剩下四个li的长度
var maxLength = this.width() - width*($li.length - 1);
//计算240的宽度 即平均宽度
var avgLength = this.width() / $li.length;
$li.mouseenter(function () {
$(this).stop().animate({width: maxLength}).siblings().stop().animate({width: width});
})
$li.mouseleave(function () {
$li.stop().animate({width: avgLength})
})
}
个人觉得其实插件跟封装一个函数差不多,在封装的后如果需要进行链式,或者需要返回值,也可在插件中添加
return this;