教你制作简单的jQuery插件
本文仅供参考,在IE6下有些bug,还如有不足或错误,请不吝赐教!
源文件及预览下载(狂击我)
怎么在博客里直接加这个,不用下载,直接打开网页看?
一、首先,制作jQuery插件需要一个闭包
1 2 3 | (function ($) { //code in here })(jQuery); |
这是来自jQuery官方的插件开发规范要求,使用这种编写方式有什么好处呢?
a) 避免全局依赖。
b) 避免第三方破坏。
c) 兼容jQuery操作符’$'和’jQuery ‘
二、有了闭包,在其中加入插件的骨架
1 2 3 4 5 6 | $.fn.dBox = function (options) { var defaults = { //各种属性及其默认值 }; var opts = $.extend(defaults, options); //function codes in here }; |
在这里dBox是我为这个弹出层插件的命名
三、为dBox建立起属性及其默认值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | $.fn.dBox = function (options) { var defaults = { opacity: 0.6, //for mask layer drag: true, title: 'dBox', content: '', left: 400, top: 200, width: 600, height: 300, setPos: false, //if use the customer’s left and top overlay: true, //if use the mask layer loadStr: 'Loading', ajaxSrc: '', iframeSrc: '' }; var opts = $.extend(defaults, options); //function codes in here }; |
四、既然是弹出窗体,那么要先设计好一个div窗体和遮罩层,在这里我将样式也直接写进去了,在function codes区域中输入如下:
1 2 3 4 5 6 7 8 9 10 11 | //build html code of the dBox var dBoxHtml = "<div id='dBox' style='background-color:#FFF;border:solid 2px #00E;position:absolute;z-index:100;'>"; dBoxHtml += "<div id='d_head' style='width:100%;height:20px;border-bottom:solid 1px #00E;'>"; dBoxHtml += "<div id='d_title' style='float:left;width:90%;color:#00E'>" + opts.title + "</div>"; dBoxHtml += "<div id='d_close' style='float:right;cursor:pointer;margin-right:5px;color:#00E'>[x]</div>"; dBoxHtml += "</div>"; dBoxHtml += "<div id='d_content' style='width:100%;height:100%;padding:3px;'>" + opts.content + "</div>"; dBoxHtml += "</div>"; var dBoxBG = "<iframe id='d_iframebg' style='position:absolute;top:0;left:0;width:0;height:0;border:none;'></iframe><div id='d_bg' style='background-color:#000;z-index:99;position:absolute;top:0;left:0;'></div>"; var loading = "<div id='d_loading' style='position:fixed;top:48%;left:48%;z-index:100;border:solid 1px #000;'>" + opts.loadStr + "</div>"; |
在IE6中,z-index对下拉列表不会起作用,所以这里遮罩层中加入id为d_iframebg的iframe作为遮罩层,这样,大体已经制作好了框架。
五、现在我们考虑要实现什么功能了首先,如何出现弹出窗体,一般都是点击,这里仍然使用点击事件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | //click event $(this).click(function () { $("body").append(dBoxHtml); //case ajax if (opts.ajaxSrc != "") { $("#d_content").append("<div id='d_ajax' style='width:" + (opts.width - 6) + "px;height:" + (opts.height - 26) + "px;overflow:scroll;'><div id='d_ajaxcontent'></div></div>"); $("#d_ajaxcontent").load(opts.ajaxSrc); } //case iframe else if (opts.iframeSrc != "") { $("#d_content").append("<iframe frameborder='0' width='" + (opts.width - 6) + "' height='" + (opts.height - 26) + "' src='" + opts.iframeSrc + "'>"); } addCSS(); //case drag if (opts.drag == true) { drag(); } $("#d_close").click(dBoxRemove); return false; }); |
最后一个return false可以去掉浏览器默认的点击事件,如在一个a标记上绑定点击事件,将不会造成默认的跳转效果


欢迎留言