jQuery implements a simple DIV drag effect
- 2020-12-22 17:33:24
- OfStack
This article illustrates jQuery's simple DIV drag effect. To share for your reference, the details are as follows:
Create 1 HTML file, copy the following code into it, modify the jquery file (go to the next one if you don't have one, I used ES7en-1.8.2), and it is ready to run
<!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=gb2312" />
<title>Jquery : Drag the mouse DIV</title>
<style type="text/css">
div#computerMove{
position:absolute;
top:50px;
left:50px;
width:200px;
height:30px;
line-height:30px;
background-color:#00CCCC;
text-align:center;
color:#FFFFFF;
cursor:default;
}
</style>
</head>
<body>
<div id="computerMove"> Click on me and drag </div>
<script src="jquery-1.8.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var $div = $("div#computerMove");
/* Bind left mouse button hold event */
$div.bind("mousedown",function(event){
/* Gets the coordinates of the node you want to drag */
var offset_x = $(this)[0].offsetLeft;//x coordinates
var offset_y = $(this)[0].offsetTop;//y coordinates
/* Gets the coordinates of the current mouse */
var mouse_x = event.pageX;
var mouse_y = event.pageY;
/* Bind drag events */
/* Because you might move the mouse out of an element when dragging, you should use global ( document ) element */
$(document).bind("mousemove",function(ev){
/* Calculate where the mouse has moved */
var _x = ev.pageX - mouse_x;
var _y = ev.pageY - mouse_y;
/* Sets the moved element coordinates */
var now_x = (offset_x + _x ) + "px";
var now_y = (offset_y + _y ) + "px";
/* Change the location of the target element */
$div.css({
top:now_y,
left:now_x
});
});
});
/* When the left mouse button is released, contact the event binding */
$(document).bind("mouseup",function(){
$(this).unbind("mousemove");
});
})
</script>
</body>
</html>
For more information about jQuery, please refer to: Summary of jQuery Dragging Effects and Techniques, Summary of jQuery Extension Techniques, Summary of jQuery Common Classic Effects, and Summary of jQuery Animation and Effects Usage.
I hope this article has been helpful in jQuery programming.