【js】元素拖拽

常用拖拽方法封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 拖拽方法
* @param {HTMLElement} sceneDom 拖拽场景
* @param {HTMLElement} dragDom 拖拽对象
*/
function rocDrag(sceneDom, dragDom) {
dragDom.onmousedown = function (event) {
// 记录鼠标在该DOM元素上的偏移位置
let x = event.pageX - dragDom.offsetLeft;
let y = event.pageY - dragDom.offsetTop;
sceneDom.onmousemove = function (event) {
const dx = event.pageX - x;
const dy = event.pageY - y;
dragDom.style.left = dx + "px";
dragDom.style.top = dy + "px";
};
sceneDom.onmouseup = function () {
sceneDom.onmousemove = null;
sceneDom.onmouseup = null;
};
};
}