Jquery编写自己的插件

来源:互联网 发布:js设置div颜色 编辑:程序博客网 时间:2024/04/30 09:56

编写自己的插件

首先我们需要搭建一个插件框架如下:

(function($){})(jQuery)

然后利用Jquery里的extend编写自己所需要用的插件:

jQuery.extend() 函数用于将一个或多个对象的内容合并到目标对象。
注意:
1. 如果只为$.extend()指定了一个参数,则意味着参数target被省略。此时,target就是jQuery对象本身。通过这种方式,我们可以为全局对象jQuery添加新的函数。
2. 如果多个对象具有相同的属性,则后者会覆盖前者的属性值。

$.extend( [deep ], target, object1 [, objectN ] )
deep    可选。 Boolean类型 指示是否深度合并对象,默认为false。如果该值为true,且多个对象的某个同名属性也都是对象,则该"属性对象"的属性也将进行合并。target  Object类型 目标对象,其他对象的成员属性将被附加到该对象上。object1 可选。 Object类型 第一个被合并的对象。objectN 可选。 Object类型 第N个被合并的对象。

下例是一个带关闭按钮的提示框

/** *  * @authors wdl (you@example.org) * @date    2017-07-26 10:04:44 * @version $Id$ */(function ($) {  $.extend({        autohideTips: function(text,delay) {            $('body').append('<div class="tipBox"><div class="autohideTips"><a href="#" class="closeTip">×</a>'+text+'<div></div>');            setTimeout(function(){                $('.autohideTips').hide();            }, delay)             $(".closeTip").on("click", function () {                $('.autohideTips').hide();            });        },    })})(jQuery); 
@charset "UTF-8";/** *  * @authors Your Name (you@example.org) * @date    2017-07-26 10:08:49 * @version $Id$ */html, body, div, ul, li, p, h1, h2, h3, h4, h5, h6, span {    margin: 0px;    padding: 0px;}ul li {    list-style: none;}.tipBox{    position: absolute;    min-width: 200px;    top: 80px;    right:5%;}.autohideTips {    border-radius: 4px;    font-size: 16px;    padding: 12px 16px;    border: 1px solid #ccc;    color: #8a6d3b;    background-color: #fcf8e3;    border-color: #faebcc;}.autohideTips a:hover{    text-decoration: none;}.closeTip{    float: right;    font-size: 21px;    font-weight: bold;    line-height: 1;    color: #000;    text-shadow: 0 1px 0 #fff;    filter: alpha(opacity=20);    opacity: .2;    text-decoration: none;} @media screen and (max-width: 500px) {.autohideTips {    font-size: 14px;}   }

调用方法:
只需在你需要的地方写入类似

$.autohideTips('已保存',4000);

即可。

是不是很简单,快去编辑自己的插件吧

原创粉丝点击