jQuery control Div drag effect complete example analysis
- 2020-05-27 04:24:07
- OfStack
This example shows how jQuery controls the Div drag effect. Share with you for your reference. The details are as follows:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> Headless document </title>
<style>
#Drigging {
width:200px;
background:#CCC;
border:solid 1px #666;
height:80px;
line-height:80px;
text-align:center;
position:absolute;
}
</style>
<script src="jquery-1.8.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
var bool=false; // Identifies whether to move the element
var offsetX=0; // The statement DIV In the current window Left value
var offsetY=0; // The statement DIV In the current window Top value
$("#Drigging").mouseover(function(){
$(this).css('cursor','move');
// When the mouse moves to drag DIV On, set the mouse style to move (move)
})
$("#Drigging").mousedown(function(){
bool=true;
// Will be pressed when the mouse moves the element bool Set to true
offsetX = event.offsetX;
// Gets the relative offset position of the mouse in the current window Left Value and assign it to offsetX
offsetY = event.offsetY;
// Gets the relative offset position of the mouse in the current window Top Value and assign it to offsetY
$(this).css('cursor','move');
}).mouseup(function(){
bool=false;
// When the mouse moves the element up bool Set to false
})
$(document).mousemove(function(){
if(!bool)// if bool for false It returns
return;
// when bool for true To execute the following code
var x = event.clientX-offsetX;
//event.clientX Gets the mouse offset relative to the client's text area
// Then subtract offsetX Get the current drag element relative to the current window X value
// Subtract the offset from the current window when the mouse first started dragging X )
var y = event.clientY-offsetY;
//event.clientY Gets the mouse offset relative to the client's text area
// Then subtract offsetX Get the current drag element relative to the current window Y value
// Subtract the offset from the current window when the mouse first started dragging Y )
$("#Drigging").css("left", x);
$("#Drigging").css("top", y);
$("#Drigging").css('cursor','move');
})
})
</script>
</head>
<body>
<div id="Drigging" style="float:left">
Drag the layer
</div>
</body>
</html>
I hope this article has been helpful to your jQuery programming.