这里通过制作一个jquery菜单插件,抛砖引玉说明如何创建jquery插件。
先来看下没有使用jquery插件机制,编写出来的代码。
- $(document).ready(function() {
- $('ul#menu li:even').addClass('even');
- $('ul#menu li a').mouseover(function() {
- $(this).animate( { paddingLeft:"20px" }, { queue:false, duration:500 });
- }).mouseout(function() {
- $(this).animate( { paddingLeft:"0" }, { queue:true, duration:500 });
- }).click(function() {
- $(this).animate( { fontSize:"20px" }, { queue:false, duration:500 });
- });
- });
虽然实现了功能,但代码一点也不优雅,没有任何的封装,没有便利的接口,不具有扩展性。
我们来把上面的代码整合成jquery的插件
- $(document).ready(function() {
- $(#menu).animateMenu({
- padding:20
- })
- });
有经常使用jquery插件的朋友就知道,这是jquery特有的但非常有效的写法。简洁、便利的接口、可移植。
此插件的接口有了,接下来具体来看其实现过程
- //为了避免冲突,你需要一个匿名函数来包装你的函数
- (function($){
- //给jQuery附加一个新的方法
- $.fn.extend({
- //这儿就是你要开发插件的名子
- pluginname: function() {
- //迭代当前匹配元素集合
- return this.each(function() {
- //插入自己的代码
- });
- }
- });
- //传递jQuery参数到函数中,
- //因此我们能使用任何有效的javascipt变量名来替换“$“符号。但是我们将坚持使用 $ (我喜欢美元符号:)
- )(jQuery);
以上代码是jquery插件的一个通用写法。
编写接口
- (function($){
- $.fn.extend({
- //options 就是供用户配置的选项
- pluginname: function(options) {
- //设置默认值
- var defaults = {
- padding: 20,
- mouseOverColor : '#000000',
- mouseOutColor : '#ffffff'
- }
- //注意这里的extend的用法
- var options = $.extend(defaults, options);
- return this.each(function() {
- var o = options;
- //code to be inserted here
- //you can access the value like this
- alert(o.padding);
- });
- }
- });
- })(jQuery);
来看其完整的js代码
- (function($){
- $.fn.extend({
- //plugin name - animatemenu
- animateMenu: function(options) {
- //Settings list and the default values
- var defaults = {
- animatePadding: 60,
- defaultPadding: 10,
- evenColor: '#ccc',
- oddColor: '#eee'
- };
- var options = $.extend(defaults, options);
- return this.each(function() {
- var o =options;
- //Assign current element to variable, in this case is UL element
- var obj = $(this);
- //Get all LI in the UL
- var items = $("li", obj);
- //Change the color according to odd and even rows
- $("li:even", obj).css('background-color', o.evenColor);
- $("li:odd", obj).css('background-color', o.oddColor);
- //Attach mouseover and mouseout event to the LI
- items.mouseover(function() {
- $(this).animate({paddingLeft: o.animatePadding}, 300);
- }).mouseout(function() {
- $(this).animate({paddingLeft: o.defaultPadding}, 300);
- });
- });
- }
- });
- })(jQuery);
设置四个可配置参数
1)、animatePadding : 给animate 效果设置”padding“值
2)、defaultPadding : 给padding设置默认的值
3)、evenColor :设置偶数行事件的颜色
4)、oddColor : 设置奇数行事件的颜色
当然还少不了建立菜单结构
- <ul id="menu">
- <li>Home</li>
- <li>Posts</li>
- <li>About</li>
- <li>Contact</li>
- </ul>

