关于鼠标拖拽的问题

半夜三更看球 半夜三更看球 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
关于拖拽的提问
在练习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>
```
...全文

相关推荐

评论 2
收藏 已收藏
分享
返回顶部
半夜三更看球
JavaScript 87,984 成员 224,681 内容