//这个是一个让DOM元素可以拖拽的控件,代码很简单,我也是新手,不知道有没有BUG,自己测试还行,希望大家发现BUG,踊跃提出,谢谢。这个是基于JQUERY开发的

所以要引入JQUERY框架。

把我的这个控件代码放到一个js文件里面直接引入就可以了

 

-------------控件代码


$.fn.myDrag = function() {

    var self = $(this);
    self.css("position", "absolute");
    var p = self.position();
    self.css({ left: p.left, top: p.top });
    self.mousedown(
        function(event) {
            // debugger;
            self.data("ifDary", "true");   //保存状态,表示是否可以拖拽
            // debugger;
            var selfLeft = event.pageX - parseInt(self.css("left")); //计算出鼠标到这个元素的left
            var selfTop = event.pageY - parseInt(self.css("top")); //计算出鼠标到这个元素的top
            self.data("selfLeft", selfLeft); //保存坐标信息
            self.data("selfTop", selfTop);

        }

    );
    $(document).mouseup(
           function() {
    self.data("ifDary", "false");
           

  //防止窗体飞到外面去
               var bWidth = $(window).width();
               var bHeight = $(window).height();
               var currentleft = parseInt(self.css("left"));
               var currenttop = parseInt(self.css("top"));
               if (currentleft <= 0)
                   currentleft = 0;
               if (currentleft >= bWidth)
                   currentleft = bWidth - self.width();
               if (currenttop <= 0)
                   currenttop = 0;
               if (currenttop >= bHeight)
                   currenttop = bHeight - self.height();

               self.css({ left: currentleft, top: currenttop });

           }
         );
    $(document).mousemove(function(event) {
        var state = self.data("ifDary");
        if (state && state == "true") {
            var selfLeft = event.pageX - parseInt(self.data("selfLeft")); //计算这个元素的left位置
            var selfTop = event.pageY - parseInt(self.data("selfTop"));
            self.css({ left: selfLeft, top: selfTop }); //设置这个元素的位置
        }
    });
    return self;
}

 

 

----------------javascript代码

<script src="../script/jquery-1.3.2.js" type="text/javascript"></script> //这个是JQUERY框架,没有的自己搜索去到处都是,一脚踩一堆

    <script src="myDrag.js" type="text/javascript"></script> //这个是我的那个控件代码

    <script type="text/javascript">
        $(function() {
            $("#div1").myDrag();
        });
    </script>

 

--------------------------HTML代码

        <div id="div1" style="background-color: Red; height: 100px; width: 100px;">
           点击拖我吧
        </div>