<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div{
width: 200px;
height: 100px;
line-height: 100px;
margin: 0 auto;
color: brown;
text-align: center;
background-color: skyblue;
position: absolute;
}
</style>
</head>
<body>
<div id="box">你拖我一个你试试</div>
<script>
//设置mosusedown
var div = document.getElementById('box')
div.onmousedown = function(e){
e = e || event
//获取当前位置
var x = e.pageX - div.offsetLeft//减去原位置的值
var y = e.pageY - div.offsetTop
//设置mosusemove
//获取移动的位置
document.onmousemove = function(e){
e = e || event
var moveX = e.pageX
var moveY = e.pageY
div.style.left = moveX - x + 'px'//移动的位置减去移动前的位置
div.style.top = moveY - y + 'px'
}
document.onmouseup = function(){
document.onmousemove = null
}
}
</script>
</body>
</html>