Code Demonstration:
Http://www.imqing.com/demo/movediv.html
General principle:
Make the position of the div absolute positioning absolute, and then control its top and left values, you need to listen to mouse events, mainly use mousedown, mousemove, mouseup.
After mousedown, record the position of the mouse and the div to be moved when mousedown, and then obtain the difference between the two to get the position of the div after the mouse moves. That is:
Left = current mouse position. x-(when you click the mouse, the. x value-the initial position of the div x value)
Top = current mouse position. y-(The. y value when the mouse is clicked-the initial position y value of the div)
Code:
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html lang = "zh">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
<Title> Qing's Web </title>
<Script src = "./jquery-1.7.2.min.js" type = "text/javascript"> </script>
<Style type = "text/css">
. Footer {
Position: fixed;
Bottom: 0;
Width: 100%;
}
. MoveBar {
Position: absolute;
Width: 250px;
Height: 300px;
Background: #666;
Border: solid 1px #000;
}
# Banner {
Background: #52 CCCC;
Cursor: move;
}
</Style>
</Head>
<Body style = "padding-top: 50px;">
<Div class = "moveBar">
<Div id = "banner"> press here to move the current div </div>
<Div class = "content"> other content </div>
</Div>
<Div class = "footer">
<P align = "center" class = "label"> ALL Rights Reserved Qing are copyrighted </p>
</Div>
<Script>
JQuery (document). ready (
Function (){
$ ('# Banner'). mousedown (
Function (event ){
Var isMove = true;
Var abs_x = event. pageX-$ ('div. movebar'). offset (). left;
Var abs_y = event. pageY-$ ('div. movebar'). offset (). top;
$ (Document). mousemove (function (event ){
If (isMove ){
Var obj = $ ('div. movebar ');
Obj.css ({'left': event. pageX-abs_x, 'top': event. pageY-abs_y });
}
}
). Mouseup (
Function (){
IsMove = false;
}
);
}
);
}
);
</Script>
</Body>
</Html>
In fact, there are not many codes, hey. The key point is that the position of the div to be moved is absolute positioning, and then the mouse event is detected. Hey.