Jquery插件的简单写法

记录下编写jquery插件的两种写法:

写法一:

View Code
(function($){

  $.fn.hoverAlert = function(options){

    var def ={message:'haha'};

    options = $.extend(def,options);

    $(this).bind("mouseover",function(){

        alert(options.message);

      }

  });

})(jQuery);

 

  

写法二:

View Code
(function($){

  $.fn.extend({ function(options){

    var def ={message:'test'};

    options = $.extend(def,options);

    $(this).bind("mouseover",function(){

        alert(options.message);

      }

    });

  }

})(jQuery);

 

引用方法:

页面中首先引入jquery 1.7 ,然后引入刚刚编写的插件js文件。

调用示例如下:

  $(document).ready(function(){

    $("#testdiv").hoverAlert(); 

    //$("#testdiv").hoverAlert({message:'弹出内容'}); 

   });

 

这里有一个弹出层的例子:

View Code
(function ($) {
    $.fn.hoverAlert = function (options) {
        var def = { width: "auto", height: "40px", message: "haha" }; //默认设置
        options = $.extend(def, options);  //合并用户自定义设置于默认设置
        //绑定事件  鼠标进入创建弹出层  鼠标移动弹出层随之移动 鼠标离开弹出层消失
        $(this).mouseenter(function (e) {
            CreateFloatDiv(this, e.pageX, e.pageY);
        }).mousemove(function (e) {
            MoveFloatDiv(e.pageX, e.pageY);
        }).mouseleave(function () { HideFloatDiv(); });

        //创建弹出层
        var CreateFloatDiv = function (me,x,y) {
            $(me).append("<div class='floatDiv1988999889' style='position:absolute;border:1px solid #cccccc;'>" + options.message + "</div>");
            var floatDiv = MoveFloatDiv(x, y);
            floatDiv.css("width", options.width)
            .css("height", options.height)
            .css("background-image", "url(img/bg.png)")
            .css("backgroun-repeat", "repeat");
        }

        //设置弹出层跟随鼠标移动
        var MoveFloatDiv = function (x,y) {
            var floatDiv = $(".floatDiv1988999889");
            floatDiv.css("left", x + "px");
            floatDiv.css("top", y + "px");
            return floatDiv;
        }

        //移除弹出层
        var HideFloatDiv = function () {
            $(".floatDiv1988999889").remove();
        }
    }
})(jQuery);

 

 Demo下载地址:https://files.cnblogs.com/fengzheng/jquery%E6%8F%92%E4%BB%B6%E5%86%99%E6%B3%95.rar

 

 

posted @ 2012-09-08 16:38  风的姿态  阅读(411)  评论(0编辑  收藏  举报