关于鼠标拖拽的问题
关于拖拽的提问
在练习JavaScript拖拽的时候突然发现使用style.left和style.top会影响第二次的鼠标拖拽,希望各位大牛解释一下这是什么原理? 请看下列代码
```
<!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>
.onc {
width: 150px;
height: 150px;
background-color: red;
position: absolute;
left: 0px;
top: 0px;
}
</style>
</head>
<body>
<div class="onc"></div>
</body>
<script>
var div = document.getElementsByTagName("div")[0];
var disX,
disY;
div.onmousedown = function (e) {
var event = e ||window.event;//解决兼容性问题
disX = e.clientX - div.offsetLeft;//此处为什么不能用div.style.left
disY = e.clientY - div.offsetTop;//此处为什么不能用div.style.top
document.onmousemove = function (e) {
div.style.left = e.clientX - disX + "px";
div.style.top = e.clientY - disY + "px";
}
document.onmouseup = function (e) {
document.onmousemove = null;
document.onmouesup = null;
}
}
</script>
</html>
```