16
2009
03

可拖动的层(jquery插件)

最近学习jquery编程,整出个可拖动的层(jquery插件),虽然这类插件在网上很多,但终究不是为自己定制的。下面写下我自己第一个jquery插件的源码吧。

jquery.drag.arain.js

// JavaScript Document
// arain
// 2009 03 03
// div drag
var listZIndex = 100; 
(function($){
$.fn.Drags= function(options){
        var lastMouseX = 0;
        var lastMouseY = 0;
        var defaults = {
            posx : 0,
            posy : 0,
            handle: this,
      draggable: true
        };
              
        var options = $.extend(defaults, options);
              
     var setFocus = function($obj){
         $obj.css("z-index",listZIndex++);
     };
           
     var move = function($obj, x, y){
         $obj.attr("lastX",x)
          .attr("lastY",y)
          .css("left", x)
             .css("top", y);
     };
     var dragging = function(e, $obj){
         if(options.draggable){
      e = e ? e : window.event;
         var newx = parseInt($obj.css("left")) + (e.clientX - lastMouseX);
            var newy = parseInt($obj.css("top")) + (e.clientY - lastMouseY);
         lastMouseX = e.clientX;
         lastMouseY = e.clientY;
             
         move($obj,newx,newy);
      }
     };
           
     $(options.handle).bind('mousedown', function(e){
         $obj = $(e.target).parent();
      setFocus($obj);
            
         if($obj.attr("state") == "normal"){
             e = e ? e : window.event;
          lastMouseX = e.clientX;
          lastMouseY = e.clientY;
                
          $(document).bind('mousemove', function(e){
           dragging(e, $obj);
          });
                
             
          $(document).bind('mouseup', function(e){
        $(document).unbind('mousemove');
        $(document).unbind('mouseup');
          });
             
         }
        });
           
     move($(this),options.posx,options.posy);
     $(this).attr("state","normal");
       
}})(jQuery);
//调用:在页面的
 $(document).ready(function(){// drag move
 $("#UserList").Drags({
     posx:50,
     posy:50,
     handle:"#UserList",
     draggable:true
 });});


呵呵,这样一个插件就写好了。

« 上一篇下一篇 »

评论列表:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。