Home  >  Article  >  Web Front-end  >  Complete example analysis of jQuery controlling Div drag and drop effect_jquery

Complete example analysis of jQuery controlling Div drag and drop effect_jquery

WBOY
WBOYOriginal
2016-05-16 16:04:121103browse

The example in this article describes how jQuery controls the drag-and-drop effect of Div. Share it with everyone 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>无标题文档</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; //标识是否移动元素
var offsetX=0; //声明DIV在当前窗口的Left值
var offsetY=0; //声明DIV在当前窗口的Top值
$("#Drigging").mouseover(function(){
$(this).css('cursor','move');
//当鼠标移动到拖拽的DIV上的时候,将鼠标的样式设置为移动(move)
})
$("#Drigging").mousedown(function(){ 
 bool=true;
 //当鼠标在移动元素按下的时候将bool设定为true
 offsetX = event.offsetX;
 //获取鼠标在当前窗口的相对偏移位置的Left值并赋值给offsetX
  offsetY = event.offsetY;
  //获取鼠在当前窗口的相对偏移位置的Top值并赋值给offsetY
 $(this).css('cursor','move');
 }).mouseup(function(){
bool=false;
//当鼠标在移动元素起来的时候将bool设定为false
})
$(document).mousemove(function(){
if(!bool)//如果bool为false则返回
return;
//当bool为true的时候执行下面的代码
var x = event.clientX-offsetX;
//event.clientX得到鼠标相对于客户端正文区域的偏移
//然后减去offsetX即得到当前推拽元素相对于当前窗口的X值
//(减去鼠标刚开始拖动的时候在当前窗口的偏移X)
var y = event.clientY-offsetY;
//event.clientY得到鼠标相对于客户端正文区域的偏移
//然后减去offsetX即得到当前推拽元素相对于当前窗口的Y值
//(减去鼠标刚开始拖动的时候在当前窗口的偏移Y)
$("#Drigging").css("left", x);
$("#Drigging").css("top", y);
$("#Drigging").css('cursor','move');
})
})
</script>
  </head>
  <body>
    <div id="Drigging" style="float:left">
      拖拽层
    </div>
  </body>
</html>

I hope this article will be helpful to everyone’s jQuery programming.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn