一、案例
```go
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#box {
width: 200px;
height: 200px;
background: red;
position: absolute;
text-align: center;
}
#box img {
width: 100px;
height: 100px;
background: brown;
}
</style>
</head>
<body>
<div id="box">
哈哈哈哈
<img src="./image/1.png" alt="">
</div>
<script>
//鼠标事件
// onmousedown 鼠标抬起
// onmousemove 鼠标移动 在onmousedown 中定义
// onmouseup 鼠标放下 在onmousedown 中定义
var box = document.getElementById('box')
//按下
box.onmousedown = function(ev) {
//兼容IE8及以下设置全局捕获,阻止默认行为
if (box.setCapture) {
box.setCapture()
}
var ev = ev || event
//获取鼠标到盒子的距离=鼠标到文档的距离-盒子到文档的距离
var clx = ev.clientX - box.offsetLeft
var cly = ev.clientY - box.offsetTop
console.log(clx, cly)
//拖动
document.onmousemove = function(ev) {
var ev = ev || event
box.style.left = ev.clientX - clx + 'px'
box.style.top = ev.clientY - cly + 'px'
}
// //抬起
box.onmouseup = function() {
// 鼠标按下的时候取消box绑定的事件
document.onmousemove = null; //这里应该改为document 移动的事件
document.onmouseup = null; //当这个元素
console.log('234567')
}
//阻止文字或是图片 进入浏览器搜索的默认行为 IE678 不支持
return false
//IE8及以下的取消全局捕获
if (box.releaseCapture) {
box.releaseCapture()
}
}
</script>
</body>
</html>