JS 鼠标拖拽元素移动

JavaScript实现鼠标拖拽元素移动

代码示例如下:

<!DOCTYPE html>
<html lang="zh-CN">

<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#wrap {
width: 100px;
height: 100px;
background-color: green;
position: absolute;
left: 100px;
top: 100px;
z-index: 100;
}
</style>
</head>

<body>
<div id="wrap"></div>
</body>
<script>
//鼠标拖拽移动
//1.为div绑定鼠标事件
//2.将鼠标坐标点与div定位位置进行关联
wrap.onmousedown = function (e) {
console.log(e);
var e = e || window.event;
//获取按下的位置
var w = e.clientX;
var h = e.clientY;
console.log('获取按下的位置', 'clientX', w, 'clientY', h);
//获得是鼠标按下时相对于元素的位置
var ex = w - wrap.offsetLeft;
var ey = h - wrap.offsetTop;

document.onmousemove = function (h) {
var h = h || window.event;
var w1 = h.clientX;
var h1 = h.clientY;
console.log('onmousemove', 'w1', w1, 'h1', h1);
wrap.style.left = (w1 - ex) + "px";
wrap.style.top = (h1 - ey) + "px";

}
}

wrap.onmouseup = function () {
document.onmousemove = null;
}
</script>

</html>
  • 运行结果:

运行结果