感谢
Teemu
我找到了解决我问题的办法。其思想是在用户不拖动时运行一个唯一的事件侦听器。当他拖动一个元素时,会添加其他事件侦听器
并在用户结束拖动过程后立即删除
mouseup
或
mouseleave
draggable
startDrag
,
dragging
和
endDrag
和信息:
element
和
offset
关于拖动机制。
为了删除事件侦听器,我需要将事件函数保存在变量中。
bind()
为了得到
的属性。所以我想到了财产
events
充满了
拖动
拖动
所以我想到:
(function() {
this.events = {
_mousemove: this.dragging.bind(this),
_mouseup: this.endDrag.bind(this)
}
}.bind(draggable))()
const _mousemove = draggable.dragging.bind(draggable)
const _mouseup = draggable.endDrag.bind(draggable)
所以现在我可以停止与
_mousemove
_mouseup
里面
最终位置
通过使用
this.events._mousemove
和
this.events._mouseup
.
现在可以添加事件侦听器:
document.addEventListener('mousemove', draggable.events._mousemove);
document.addEventListener('mouseup', draggable.events._mouseup);
以下是完整的JavaScript代码:
const draggable = {
events: {},
startDrag: function(event) {
this.element = event.target
const rect = event.target.getBoundingClientRect();
this.offset = [event.clientX - rect.x, event.clientY - rect.y];
},
dragging: function(e) {
this.element.style.left = `${e.clientX - this.offset[0]}px`;
this.element.style.top = `${e.clientY - this.offset[1]}px`;
},
endDrag: function() {
document.removeEventListener('mousemove', this.events._mousemove)
document.removeEventListener('mouseup', this.events._mouseup)
},
element: '',
offset: []
};
document.addEventListener('mousedown', e => {
(function() {
this.events = {
_mousemove: this.dragging.bind(this),
_mouseup: this.endDrag.bind(this)
}
}.bind(draggable))()
if (e.target.classList.contains('draggable')) {
draggable.startDrag(e)
document.addEventListener('mousemove', draggable.events._mousemove);
document.addEventListener('mouseup', draggable.events._mouseup);
}
});
.box {
width: 100px;
height: 100px;
background: pink;
position: absolute;
user-select: none;
}
.box:nth-child(1) {
background: lightblue;
top: 125px;
left: 125px;
}
.box:nth-child(2) {
background: lightgreen;
top: 250px;
left: 250px;
}
<div class="draggable box"></div>
<div class="draggable box"></div>
<div class="draggable box"></div>