<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JS拖拽div(移动)-jq22.com</title>
<script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
<style>
#dv {
width: 100px;
height: 100px;
background-color: blue;
border-radius: 50%;
position: absolute;
}
</style>
</head>
<body>
<div id="dv" onmousedown="mouseDown(this,event)" onmousemove="mouseMove(event)" onmouseup="mouseUp(event)"></div>
<script>//这个是网上摘录的。
var mouseX, mouseY,div;
var objX, objY;
var isDowm = false;
function mouseDown(obj, e) {
div = obj;
obj.style.cursor = "move";
objX = div.offsetLeft;
objY = div.offsetTop;
mouseX = e.clientX;
mouseY = e.clientY;
isDowm = true;
}
function mouseMove(e) {
var x = e.clientX;
var y = e.clientY;
if (isDowm) {
div.style.left = parseInt(objX) + parseInt(x) - parseInt(mouseX) + "px";
div.style.top = parseInt(objY) + parseInt(y) - parseInt(mouseY) + "px";
}
}
function mouseUp(e) {
if (isDowm) {
var x = e.clientX;
var y = e.clientY;
div.style.left = parseInt(objX) + parseInt(x) - parseInt(mouseX) + "px";
div.style.top = parseInt(objY) + parseInt(y) - parseInt(mouseY) + "px";
div.style.cursor = "default";
isDowm = false;
}
}
</script>
<script>//这个是我改造的一个。
//获取元素
var dv;
var x = 0;
var y = 0;
var l = 0;
var t = 0;
var isDown = false;
//鼠标按下事件
function mouseDown(obj, e) {
dv = obj;//document.getElementById('dv');
//获取x坐标和y坐标
x = e.clientX;
y = e.clientY;
//获取左部和顶部的偏移量
l = dv.offsetLeft;
t = dv.offsetTop;
//开关打开
isDown = true;
//设置样式
dv.style.cursor = 'move';
}
function mouseMove(e) {
if (isDown == false) {
return;
}
//获取x和y
var nx = e.clientX;
var ny = e.clientY;
//计算移动后的左偏移量和顶部的偏移量
var nl = nx - (x - l);
var nt = ny - (y - t);
dv.style.left = nl + 'px';
dv.style.top = nt + 'px';
}
function mouseUp(e) {
isDown = false;
dv.style.cursor = 'default';
}
</script>
</body>
</html>