JQuery编写自己的插件(七)

一:jQuery插件的编写基础
1、插件的种类
编写插件的目的是给一系列已经方法或函数做一个封装,以便在其他地方重复使用,方便后期维护和提高开发效率。
常见的种类有以下三种:
封装对象方法的插件

二:编写自己的插件
1、封装jQuery对象方法的插件
Step1:框架
;(
    function($) {
    $.fn.extend({
        ….
        });
    }
)(jQuery)

实例:改变背景色

;(
    function($) {
        $.fn.extend({
            "color": function(value) {
                return this.css("color", value);
            },
            "bgcolor": function(value) {
                return this.css("background-color", value);
            }
        });
    }
)(jQuery)

调用:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>

    <script src="Scripts/jquery-1.2.6.js" type="text/javascript"></script>

    <script src="Scripts/jquery-1.2.6-vsdoc-cn.js" type="text/javascript"></script>
    <script src="Scripts/jquery.color.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function() {
        $("div").click(function() {
                $(this).bgcolor(this.innerText);
            });
        });
    </script>
</head>
<body>
<div>red</div>
<div>blue</div>
<div>green</div>
</body>
</html>

2.编写全局函数插件

Step1:写一个封装全局函数的插件

;(

function($) {

$.extend({

….

});

}

)(jQuery)

代码:去除空格

;(
    function($) {
        $.extend({
            ltrim: function(text) {
                return text.replace(/^\s+/g, "");
            },
            rtrim: function(text) {
                return text.replace(/\s+$/g, "");
            }
        });
    }
)(jQuery)

调用:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.2.6.js" type="text/javascript"></script>
    <script src="Scripts/jquery-1.2.6-vsdoc-cn.js" type="text/javascript"></script>
    <script src="Scripts/jquery.trim.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            var teststr = "      test   ";
            alert(teststr.length);
            var s1 = $.ltrim(teststr);
            alert(s1.length);
            var s2 = $.rtrim(teststr);
            alert(s2.length);
        });
    </script>
</head>
<body>
</body>
</html>

3.编写自已的插件-MyModalForm
Step1:写一个封装全局函数的插件
;(
    function($) {
    $.extend({
        ….
        });
    }
)(jQuery)

效果:

代码:

;(
    function($) {
        var divW; //DIV宽度
        var divH; //DIV高度
        var clientH; //浏览器高度
        var clientW; //浏览器宽度
        var divTitle; //DIV标题
        var pageUrl; //DIV中加载的页面
        var div_X; //DIV横坐标
        var div_Y; //DIV纵坐标
        $.extend({
            //清除背景锁定
            clearLockScreen: function() {
                $("#divLock").remove();
            },

            //清除DIV窗口
            clearDivWindow: function() {
                $("#divWindow").remove();
            },
            //返回弹出的DIV的坐标
            divOpen: function() {
                var minTop = 80; //弹出的DIV记顶部的最小距离
                if ($("#divWindow").length == 0) {
                    clientH = $(window).height(); //浏览器高度
                    clientW = $(window).width(); //浏览器宽度
                    div_X = (clientW - divW) / 2; //DIV横坐标
                    div_Y = (clientH - divH) / 2; //DIV纵坐标
                    div_X += window.document.documentElement.scrollLeft; //DIV显示的实际横坐标
                    div_Y += window.document.documentElement.scrollTop; //DIV显示的实际纵坐标
                    if (div_Y < minTop) {
                        div_Y = minTop;
                    }
                    $("body").append("<div id=‘divWindow‘><div id=‘divTitle‘><img src=‘images/Close-1.gif‘ id=‘x‘ /></div><div id=‘divContent‘>载入中...</div></div>"); //增加DIV
                    //divWindow的样式
                    $("#divWindow").css("position", "absolute");
                    $("#divWindow").css("z-index", "200");
                    $("#divWindow").css("left", (div_X + "px")); //定位DIV的横坐标
                    $("#divWindow").css("top", (div_Y + "px")); //定位DIV的纵坐标
                    $("#divWindow").css("opacity", "0.9");
                    $("#divWindow").width(divW);
                    $("#divWindow").height(divH);
                    $("#divWindow").css("background-color", "#FFFFFF");
                    $("#divWindow").css("border", "solid 1px #333333");
                    //divTitle的样式
                    $("#divTitle").css("height", "20px");
                    $("#divTitle").css("line-height", "20px");
                    $("#divTitle").css("background-color", "#333333");
                    $("#divTitle").css("padding", "3px 5px 1px 5px");
                    $("#divTitle").css("color", "#FFFFFF");
                    $("#divTitle").css("font-weight", "bold");
                    //x的样式
                    $("#x").css("float", "right");
                    $("#x").css("cursor", "pointer");
                    //divContent的样式
                    $("#divContent").css("padding", "10px");
                }
                else {
                    clientH = $(window).height(); //浏览器高度
                    clientW = $(window).width(); //浏览器宽度
                    div_X = (clientW - divW) / 2; //DIV横坐标
                    div_Y = (clientH - divH) / 2; //DIV纵坐标
                    div_X += window.document.documentElement.scrollLeft; //DIV显示的实际横坐标
                    div_Y += window.document.documentElement.scrollTop; //DIV显示的实际纵坐标
                    if (div_Y < minTop) {
                        div_Y = minTop;
                    }
                    $("#divWindow").css("left", (div_X + "px")); //定位DIV的横坐标
                    $("#divWindow").css("top", (div_Y + "px")); //定位DIV的纵坐标
                }
            },
            //锁定背景屏幕
            lockScreen: function() {
                if ($("#divLock").length == 0) {	//判断DIV是否存在
                    clientH = $(window).height(); //浏览器高度
                    clientW = $(window).width(); //浏览器宽度
                    $("body").append("<div id=‘divLock‘></div>")	//增加DIV
                    $("#divLock").height(clientH);
                    $("#divLock").width(clientW);
                    $("#divLock").css("display", "block");
                    $("#divLock").css("background-color", "#000000");
                    $("#divLock").css("position", "fixed");
                    $("#divLock").css("z-index", "100");
                    $("#divLock").css("top", "0px");
                    $("#divLock").css("left", "0px");
                    $("#divLock").css("opacity", "0.5");
                }
                else {
                    clientH = $(window).height(); //浏览器高度
                    clientW = $(window).width(); //浏览器宽度
                    $("#divLock").height(clientH);
                    $("#divLock").width(clientW);
                }
            },
            ShowModalForm: function(divWidth, divHeight, title, url) {
                divW = divWidth; //DIV宽度
                divH = divHeight; //DIV高度
                divTitle = title; //DIV高度
                pageUrl = url; //DIV中加载的页面UR
                $.lockScreen(); //锁定背景
                $.divOpen();
                $("#divTitle").append(divTitle);
                $("#divContent").load(pageUrl, function() {
                    //加上拖动的效果
                    $.AttachDrag("divWindow");
                });
                //交换X图片
                $("#x").hover(
		                            function() {
		                                $(this).attr("src", "images/Close-2.gif");
		                            },
		                            function() {
		                                $(this).attr("src", "images/Close-1.gif");
		                            }
	                            );

                //关闭DIV窗口
                $("#x").click(
		                            function() {
		                                $.clearDivWindow();
		                                $.clearLockScreen();
		                            });
                //窗口大小改变时
                $(window).resize(
		                                    function() {
		                                        if ($("#divLock").length != 0) {
		                                            $.lockScreen();
		                                        }
		                                        if ($("#divWindow").length != 0) {
		                                            $.divOpen();
		                                        }
		                                    }
                                    );
            }
        });
    }
)(jQuery)

调用的代码:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Demo3.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>封装全局函数的插件Demo</title>
    <link href="CSS/Main.css" rel="stylesheet" type="text/css" />

    <script src="Scripts/jquery-1.2.6.js" type="text/javascript"></script>

   <%-- <script src="Scripts/jquery-1.2.6-vsdoc-cn.js" type="text/javascript"></script>--%>
       //拖动的js       <script src="Scripts/jquery.modalform.js" type="text/javascript"></script>     //弹出窗体  注意引用的顺序
   <script src="Scripts/jquery.modalform.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function() {
        $("a").click(function() {
            $.ShowModalForm(500, 320, ‘封装全局函数的插件Demo‘, ‘GetStudentInfo.aspx‘);
            });
        });
    </script>
</head>

<body><a href="javascript:void(0)">点此演示</a>
</body>
</html>

CSS样式:

@charset "utf-8";
* {
	margin: 0px;
	padding: 0px;
}
/* download by http://www.codefans.net */
body {
	margin: 50px;
	font-family: Arial, "宋体";
	font-size: 12px;
}

四:隔行变色:

效果:

插件代码:

jquery.alterBgColor.js

; (function($) {
    $.fn.extend({
        "alterBgColor": function(options) {
            options = $.extend({
                odd: "odd", //偶数行的样式
                even: "even", //奇数行的样式
                selected: "selected" //选中行的样式
            }, options);
            $("tbody>tr:odd", this).addClass(options.odd);
            $("tbody>tr:even", this).addClass(options.even);
            $("tbody>tr", this).click(function() {
                //判断当前是否选中
                var hasSelected = $(this).hasClass(options.selected);
                //如果已经有了selected样式,则移除,否则则添加上selected样式
                //$(this)[hasSelected ? "removeClass" : "addClass"](options.selected);
                if (hasSelected)
                    $(this).removeClass(options.selected).find(":checkbox").attr("checked", false);
                else
                    $(this).addClass(options.selected).find("checkbox").attr("checked", true);

            });

            //如果有行checkbox选中的,默认情况下,让背景高亮度
            $("tbody>tr:has(:checked)", this).addClass(options.selected);

            return this;  //返回一个jquery 对象,让此方法可链
        }
    });
})(jQuery);

调用的代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
	<style type="text/css">
	table		{ border:0;border-collapse:collapse;}
	td	{ font:normal 12px/17px Arial;padding:2px;width:100px;}
	th			{ font:bold 12px/17px Arial;text-align:left;padding:4px;border-bottom:1px	solid #333;}
	.even		{ background:#FFF38F;}  /* 偶数行样式*/
	.odd		{ background:#FFFFEE;}  /* 奇数行样式*/
	.selected	{ background:#FF6500;color:#fff;}
	</style>
	<!--   引入jQuery -->

    <script src="Scripts/jquery-1.2.6.js" type="text/javascript"></script>

    <script src="Scripts/jquery.alterBgColor.js" type="text/javascript"></script>
	<script type="text/javascript">

	//插件应用
	$(function(){
		$("#table2")
				.alterBgColor()  //应用插件
				.find("th").css("color","red");//可以链式操作
	})

</script>
</head>
<body>
<table id="table1">
	<thead><tr><th> </th><th>姓名</th><th>性别</th><th>暂住地</th></tr></thead>
	<tbody>
		<tr>
			<td><input type="checkbox" name="choice" value=""/></td>
			<td>张山</td>
			<td>男</td>
			<td>浙江宁波</td>
		</tr>
		<tr>
			<td><input type="checkbox" name="choice" value="" /></td>
				<td>李四</td>
			<td>女</td>
			<td>浙江杭州</td>
		</tr>
		<tr>
			<td><input type="checkbox" name="choice" value="" checked="checked" /></td>
					<td>王五</td>
			<td>男</td>
			<td>湖南长沙</td>
		</tr>
		<tr>
			<td><input type="checkbox" name="choice" value="" /></td>
			<td>找六</td>
			<td>男</td>
			<td>浙江温州</td>
		</tr>
		<tr>
		<td><input type="checkbox" name="choice" value="" /></td>
				<td>Rain</td>
			<td>男</td>
			<td>浙江杭州</td>
		</tr>
		<tr>
			<td><input type="checkbox" name="choice" value="" checked="checked" /></td>
			<td>MAXMAN</td>
			<td>女</td>
			<td>浙江杭州</td>
		</tr>
	</tbody>
</table>
<br /><br />
<table id="table2">
	<thead><tr><th> </th><th>姓名</th><th>性别</th><th>暂住地</th></tr></thead>
	<tbody>
		<tr>
			<td><input type="checkbox" name="choice" value=""/></td>
			<td>张山</td>
			<td>男</td>
			<td>浙江宁波</td>
		</tr>
		<tr>
			<td><input type="checkbox" name="choice" value="" /></td>
				<td>李四</td>
			<td>女</td>
			<td>浙江杭州</td>
		</tr>
		<tr>
			<td><input type="checkbox" name="choice" value="" checked="checked" /></td>
					<td>王五</td>
			<td>男</td>
			<td>湖南长沙</td>
		</tr>
		<tr>
			<td><input type="checkbox" name="choice" value="" /></td>
			<td>找六</td>
			<td>男</td>
			<td>浙江温州</td>
		</tr>
		<tr>
		<td><input type="checkbox" name="choice" value="" /></td>
				<td>Rain</td>
			<td>男</td>
			<td>浙江杭州</td>
		</tr>
		<tr>
			<td><input type="checkbox" name="choice" value="" checked="checked" /></td>
			<td>MAXMAN</td>
			<td>女</td>
			<td>浙江杭州</td>
		</tr>
	</tbody>
</table>
</body>
</html>

五:鼠标拖动:myDragLibrary.js

var MyDragHandler = {
    DragPanelId: "divContext",
    _idiffx: 0,
    _idiffy: 0,
    _Div: null,
    AttachDrag: function(dragId) {
        if (dragId)
            MyDragHandler._Div = document.getElementById(dragId);
        else
            MyDragHandler._Div = document.getElementById(MyDragHandler.DragPanelId);
        document.body.onmousedown = MyDragHandler._handleMouseDown;

    },
    _handleMouseDown: function() {
        var oEvent = window.event;
        if (MyDragHandler._Div) {
            MyDragHandler._idiffx = oEvent.clientX - MyDragHandler._Div.offsetLeft;
            MyDragHandler._idiffy = oEvent.clientY - MyDragHandler._Div.offsetTop;
            document.body.onmousemove = MyDragHandler._handleMouseMove;
            document.body.onmouseup = MyDragHandler._handleMouseUp;
        }
    },
    _handleMouseMove: function() {
        var oEvent = window.event;
        MyDragHandler._Div.style.left = oEvent.clientX - MyDragHandler._idiffx;
        MyDragHandler._Div.style.top = oEvent.clientY - MyDragHandler._idiffy;
        MyDragHandler._Div.style.cursor = "move";
    },
    _handleMouseUp: function() {
        document.body.onmousemove = null;
        document.body.onmouseup = null;
        MyDragHandler._Div.style.cursor = "default";
    }
}

调用的代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
      <style type="text/css">
            #div1 {
                background-color: red;
                height: 100px;
                width: 100px;
                position: absolute;
            }
        </style>

    <script src="Scripts/jquery-1.2.6.js" type="text/javascript"></script>
    <script src="Scripts/jquery.myDragLibrary.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function() {

            $.AttachDrag("div1");
        });
    </script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
时间: 2024-08-26 13:05:36

JQuery编写自己的插件(七)的相关文章

用jquery编写的分页插件

源码 function _pager_go(total_page) { var page_str = $("#_pager_textbox").val(); var int_expr = /^(\+|-)?\d+$/; if (!int_expr.test(page_str)) { alert("请输入整数"); return; } var go_page = parseInt(page_str); if (go_page < 1 || go_page >

用jquery编写的tab插件

源码 $.fn.ss_tab = function (options) { var box = $(this); var btns = $(this).find("ul:first > li"); //console.log($(btns).length); var contents = $(this).find("ul").eq(1).children("li"); //console.log($(contents).length); $

jquery编写插件的方法

版权声明:作者原创,转载请注明出处! 编写插件的两种方式: 1.类级别开发插件(1%) 2.对象级别开发(99%) 类级别的静态开发就是给jquery添加静态方法,三种方式 1.添加新的全局函数 2.使用$.extend(obj) 3.使用命名空间 类级别开发插件(用的非常少,1%) 分别举例: //1.直接给jquer添加全局函数 jQuery.myAlert=function (str) { alert(str); }; //2.用extend()方法.extend是jquery提供的一个方

再谈:jquery编写插件的方法

版权声明:作者原创,转载请注明出处! 编写插件的两种方式: 1.类级别开发插件(1%) 2.对象级别开发(99%) 类级别的静态开发就是给jquery添加静态方法,三种方式 1.添加新的全局函数 2.使用$.extend(obj) 3.使用命名空间 类级别开发插件(用的非常少,1%) 分别举例: //1.直接给jquer添加全局函数 jQuery.myAlert=function (str) { alert(str); }; //2.用extend()方法.extend是jquery提供的一个方

jquery编写插件(转)

阅读目录 基本方法 支持链式调用 让插件接收参数 面向对象的插件开发 关于命名空间 关于变量定义及命名 压缩的好处 工具 GitHub Service Hook 原文:http://www.cnblogs.com/Wayou/p/jquery_plugin_tutorial.html 要说jQuery 最成功的地方,我认为是它的可扩展性吸引了众多开发者为其开发插件,从而建立起了一个生态系统.这好比大公司们争相做平台一样,得平台者得天下.苹果,微软,谷歌等巨头,都有各自的平台及生态圈. 学会使用j

支持多文件上传的jQuery文件上传插件Uploadify

支持多文件上传的jQuery文件上传插件Uploadify,目前此插件有两种版本即Flash版本和HTML5版本,对于HTML5版本会比较好的支持手机浏览器,避免苹果手机Safari浏览器不支持Flash,主要特性:支持多文件上传.HTML5版本可拖拽上传.实时上传进度条显示.强大的参数定制功能,如文件大小.文件类型.按钮图片定义.上传文件脚本等. Flash版本使用方法: 1.加载JS和CSS ? 1 2 3 <script src="jquery/1.7.1/jquery.min.js

强大的支持多文件上传的jQuery文件上传插件Uploadify

支持多文件上传的jQuery文件上传插件Uploadify,目前此插件有两种版本即Flash版本和HTML5版本,对于HTML5版本会比较好的支持手机浏览器,避免苹果手机Safari浏览器不支持Flash,主要特性:支持多文件上传.HTML5版本可拖拽上传.实时上传进度条显示.强大的参数定制功能,如文件大小.文件类型.按钮图片定义.上传文件脚本等. Flash版本使用方法: 1.加载JS和CSS ? 1 2 3 <script src="jquery/1.7.1/jquery.min.js

jQuery自定义滚动条样式插件mCustomScrollbar

如果你构建一个很有特色和创意的网页,那么肯定希望定义网页中的滚动条样式,这方面的 jQuery 插件比较不错的,有两个:jScrollPane 和 mCustomScrollbar. 关于 jScrollPane,大家见过的可能比较多,但是这个插件太过于古老而且功能不强大,效果在几年前非常不错,但是放在现在就不好说了.所以我选择了后者:mCustomScrollbar.下图是两者官方示例的简单对比: 本文就是介绍如何使用 mCustomScrollbar 这个插件,大部分的内容是翻译自 mCus

(转)强大的JQuery表单验证插件 FormValidator使用介绍

jQuery formValidator表单验证插件是客户端表单验证插件.在做B/S开发的时候,我们经常涉及到很多表单验证,例如新用户注册,填写个人资料,录入一些常规数据等等.在这之前,页面开发者(JavaScript开发者)需要编写大量的JavaScript来进行表单元素的校验,而这些校验在平时开发中不停的重复书写.常见的校验如不能为空,必须满足长度要求,必须为数字,必须为Email等等.一般要判断的表单元素比较多,开发过程就显得枯燥无味--重复的代码不断重复,而且可能还要兼容多种浏览器,更多