Jquery custom window arbitrary drag and drop

  • 2020-03-30 02:20:14
  • OfStack

We often see on web pages that when a button is clicked, a custom window pops up and can be dragged and dropped to change its position

If you use jquery to drag and drop, you must need jquery files.

1. Introduce jquery files

2. Write js script

Specific code:

HTML code:
 
<button id="show"> According to </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 styles:
 
<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:
 
<script language="javascript" type="text/javascript"> 
$(function(){ 
// Drag and drop  
dragAndDrop(); 
//Initialization position
initPosition(); 
//Click on the button
clickShowBtn(); 
}); 
// Drag and drop  
function dragAndDrop(){ 
var _move=false;//Mobile tag
var _x,_y;//The position of the mouse relative to 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 transparently  
}); 
$(document).mousemove(function(e){ 
if(_move){ 
var x=e.pageX-_x;//When moving the mouse position calculates the absolute position of the upper left corner of the control
var y=e.pageY-_y; 
$(".win").css({top:y,left:x});//Control new location
} 
}).mouseup(function(){ 
_move=false; 
//$(".wTop").fadeTo("fast",1);// Release the mouse and stop moving and return to opaque  
}); 
} 
//Initializes the location of the drag div
function initPosition(){ 
// To calculate Initialization position
var itop=($(document).height()-$(".win").height())/2; 
var ileft=($(document).width()-$(".win").width())/1.8; 
//Sets the location of the div to be dragged
$(".win").css({top:itop,left:ileft}); 
} 
//Click the display button
function clickShowBtn(){ 
$("#show").click(function(){ 
$(".win").show(1000); 
}); 

$("#hidden").click(function(){ 
$(".win").hide(1000); 
}); 
} 
</script> 

Introduced js file
 
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script> 

Related articles: