This is a control that allows DOM elements to be dragged. The code is very simple. I am a newbie. I don't know if there are any bugs. I can test it myself. I hope you will find bugs and raise them enthusiastically. Thank you. This is based on JQUERY, so we need to introduce the JQUERY framework.
Put my control code into a js file and introduce it directly.
Control Code
The Code is as follows:
$. 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"); // save status, indicating whether to drag
// Debugger;
Var selfLeft = event. pageX-parseInt(self.css ("left"); // calculate the left
Var selfTop = event. pageY-parseInt(self.css ("top"); // calculate the top
Self. data ("selfLeft", selfLeft); // save coordinate information
Self. data ("selfTop", selfTop );
}
);
$ (Document). mouseup (
Function (){
Self. data ("ifDary", "false ");
// Prevent the form from flying outside
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"); // calculates the left position of the element.
Var selfTop = event. pageY-parseInt (self. data ("selfTop "));
Self.css ({left: selfLeft, top: selfTop}); // you can specify the position of the element.
}
});
Return self;
}
Javascript code
The Code is as follows: