Therefore, we need to introduce the JQUERY framework.
Put my control code into a js file and introduce it directly.
Control Code
Copy codeThe 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
Copy codeThe Code is as follows:
<Script src = ".. /script/jquery-1.3.2.js "type =" text/javascript "> </script> // This is the JQUERY framework, no self-search everywhere, one foot on a pile
<Script src = "myDrag. js" type = "text/javascript"> </script> // This Is My control code.
<Script type = "text/javascript">
$ (Function (){
$ ("# Div1"). myDrag ();
});
</Script>
HTML code
Copy codeThe Code is as follows:
<Div id = "div1" style = "background-color: Red; height: 100px; width: 100px;">
Click drag me
</Div>