Home >Web Front-end >JS Tutorial >jquery implements div drag effect function (with code)

jquery implements div drag effect function (with code)

php中世界最好的语言
php中世界最好的语言Original
2018-04-25 17:31:401514browse

This time I will bring you jquery to implement the div drag effect function (with code). What are the precautions for jquery to implement the div drag effect function. The following is a practical case, let's take a look.

<!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; //声明p在当前窗口的Left值
var offsetY=0; //声明p在当前窗口的Top值
$("#Drigging").mouseover(function(){
$(this).css('cursor','move');
//当鼠标移动到拖拽的p上的时候,将鼠标的样式设置为移动(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>
    <p id="Drigging" style="float:left">
      拖拽层
    </p>
  </body>
</html>

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Json operation date format

##How can Jsonp solve ajax cross-domain

Let Ajax achieve asynchronous refresh without using plug-ins

The above is the detailed content of jquery implements div drag effect function (with code). For more information, please follow other related articles on the PHP Chinese website!

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