<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
div{
position: absolute;
width: 200px;
height: 200px;
background-color: #ccc;
}
</style></head>
<body style="position:relative;">
<div style="top:50px;left:100px;">
我是可以被拖拽的
</div> <div style="top:100px;left:300px;">
我是可以被拖拽的
</div> <script type="text/javascript">
var div = document.getElementsByTagName('div')[0];
var mouseX = 0,mouseY=0;
var divY = 0;//parseInt(div.style.top); //当前元素 与窗口左上角 距离
var divX = 0;//parseInt(div.style.left); console.info(div.style.top,div.style.left);
div.onmousedown =function(e){
//鼠标按下:
//1.获取当前元素的位置
//2.获取鼠标的位置
divY = parseInt(div.style.top); //当前元素 与窗口左上角 距离
divX = parseInt(div.style.left);
e = e || event;
mouseX = e.clientX;
mouseY = e.clientY; console.info(mouseX,mouseY);
//记录当前鼠标的位置
//div.onmousemove = function(e){
document.onmousemove = function(e){
e = e || event; //获取鼠标的新位置
var currentX = e.clientX;
var currentY = e.clientY; //计算元素的新位置
var divNewX = divX - mouseX + currentX;
var divNewY = divY - mouseY + currentY;
div.style.top = divNewY + "px";
div.style.left = divNewX + "px"; console.info("onmousemove",divNewX,divNewY);
}
}
div.onmouseup =function(e){ //div.onmousemove = null;
document.onmousemove = null;
console.info("onmouseup") }
</script>
</body></html>