<head>
<meta charset="UTF-8">
<title></title>
<style>
body {
margin: 0;
padding: 0;
}
div {
/*border: 1px solid black;*/
position: absolute;
width: 240px;
height: 240px;
background-color: powderblue;
}
div:hover {
cursor: move;
}
</style>
<script>
var div_x, div_y; //获取div的坐标
var move_x, move_y; //获取鼠标按下时的时事坐标
var new_div_x, new_div_y, new_move_x, new_move_y; //获取鼠标移动后div与鼠标按下时的坐标
var move_div_x, move_div_y; //鼠标按下时,鼠标与div的偏移量
var isDown = false; //记录鼠标的事实状态
var move_div; //要操作的div对象
// 鼠标按下事件
function down() {
// 判断鼠标是否按下
move_div = document.getElementById("mouse");
isDown = true;
//获取div的坐标
div_x = move_div.offsetLeft;
div_y = move_div.offsetTop;
//获取鼠标按下时的时事坐标
move_x = event.clientX;
move_y = event.clientY;
//获取鼠标与div的偏移量
move_div_x = move_x - div_x;
move_div_y = move_y - div_y;
}
// 鼠标松开事件
function up() {
isDown = false;
}
// 鼠标移动事件
function move() {
move_div = document.getElementById("mouse");
//时事更新div的坐标
div_x = move_div.offsetLeft;
div_y = move_div.offsetTop;
//获取鼠标移动后的事实坐标
new_move_x = event.clientX;
new_move_y = event.clientY;
if(isDown) {
//获取新的div的坐标:鼠标时事坐标-鼠标与div的偏移量
new_div_x = new_move_x - move_div_x;
new_div_y = new_move_y - move_div_y;
//将新的div的坐标赋值给di对象
move_div.style.left = new_div_x + "px";
move_div.style.top = new_div_y + "px";
}
}
</script>
</head>
<body>
<div id="mouse" onmousemove="move()" onmouseup="up()" onmousedown="down(event)">
</div>
</body>