On the web page, we often see that when you click a button, a custom window is displayed, and you can drag it to change its location.
To use jquery to implement drag-and-drop operations, the jquery file is required. The implementation steps are as follows:
1. Introduce the jquery File
2. Compile js scripts
Code:
Html code:
Copy codeThe Code is as follows:
<Button id = "show"> display </button>
<Div class = "win">
<Div class = "wTop"> <p style = "float: right; margin: 5px 5px 0px 0px; color: white "id =" hidden "> X </p> </div>
<Div class = "content"> </div>
</Div>
Css style:
Copy codeThe Code is as follows:
<Style type = "text/css">
. Win {width: 500px; height: 600px; background: #000000; border-radius: 8px; box-shadow: 0px 0px 5px 10px; opacity: 0.8; position: absolute; left: 0; top: 0; display: none}
. Win. wTop {height: 30px; width: 100%; cursor: move}
. Win. content {height: 570px; width: 100%; border-radius: 5px; background: white}
</Style>
Js script:
Copy codeThe Code is as follows:
<Script language = "javascript" type = "text/javascript">
$ (Function (){
// Drag
DragAndDrop ();
// Initialization location
InitPosition ();
// Click the button
ClickShowBtn ();
});
// Drag
Function dragAndDrop (){
Var _ move = false; // move the tag
Var _ x, _ y; // the relative position of the cursor in the upper left corner of the control.
$ (". WTop"). mousedown (function (e ){
_ Move = true;
_ X = e. pageX-parseInt ($ (". win" ).css ("left "));
_ Y = e. pageY-parseInt ($ (". win" ).css ("top "));
// $ (". WTop"). fadeTo (20, 0.5); // click to start dragging and display it transparently
});
$ (Document). mousemove (function (e ){
If (_ move ){
Var x = e. pageX-_ x; // when you move the cursor, the absolute position in the upper left corner of the control is calculated.
Var y = e. pageY-_ y;
$ (". Win" ).css ({top: y, left: x}); // new control position
}
}). Mouseup (function (){
_ Move = false;
// $ (". WTop"). fadeTo ("fast", 1); // stop moving with the mouse removed and restore to Opacity
});
}
// Initialize the position of the drag div
Function initPosition (){
// Calculate the initialization location
Var itop = ($ (document). height ()-$ (". win"). height ()/2;
Var ileft = ($ (document). width ()-$ (". win"). width ()/1.8;
// Set the position of the div to be dragged
$ (". Win" ).css ({top: itop, left: ileft });
}
// Click the Show button.
Function clickShowBtn (){
$ ("# Show"). click (function (){
$ (". Win"). show (1000 );
});
$ ("# Hidden"). click (function (){
$ (". Win"). hide (1000 );
});
}
</Script>
Introduced js files
Copy codeThe Code is as follows:
<Script type = "text/javascript" src = "js/jquery-1.10.2.min.js"> </script>