- 说明
- 3个事件:分别对应三个阶段
- dragenter拖拽进去
- dragover拖拽悬停
- drop拖拽释放
-
let drag = document.querySelector('#drag')
drag.addEventListener('dragenter', function (e) {
e.stopPropagation();
e.preventDefault();
})
drag.addEventListener('dragover', function (e) {
e.stopPropagation();
e.preventDefault();
})
drag.addEventListener('drop', function (e) {
e.stopPropagation();
e.preventDefault();
console.log(e.dataTransfer.files);
})
- [] 使用鼠标事件实现拖拽
-
- [传统事件方式]
-
let move = document.querySelector('.move');
move.onmousedown = function (e) {
let left = e.clientX - move.offsetLeft;
let top = e.clientY - move.offsetTop;
move.onmousemove = function (ev) {
move.style.left = ev.clientX - left + 'px';
move.style.top = ev.clientY - top + 'px';
}
move.onmouseup = function () {
move.onmousemove = null;
}
}
- [事件侦听方式]
- .为了避免移动速度过快导致鼠标移动到元素外面,给文档mousemove事件和mouseup事件
- .限制在当前视口移动:上下左右移动
-
move.addEventListener('mousedown', fmd);
move.addEventListener('mouseup', fmu);
let leftPos, topPos;
function fmd(e) {
leftPos = e.clientX - move.offsetLeft;
topPos = e.clientY - move.offsetTop;
document.addEventListener('mousemove', fmm);
}
function fmm(e) {
let disX = e.clientX - leftPos;
let disY = e.clientY - topPos;
if (disX < 0) {
disX = 0;
} else if (disX >= document.documentElement.clientWidth - move.offsetWidth) {
disX = document.documentElement.clientWidth - move.offsetWidth;
}
console.log(document.documentElement.clientHeight);
if (disY < 0) {
disY = 0;
} else if (disY > document.documentElement.clientHeight - move.offsetHeight) {
disY = document.documentElement.clientHeight - move.offsetHeight;
}
move.style.left = disX + 'px';
move.style.top = disY + 'px';
}
function fmu() {
document.removeEventListener('mousemove', fmm);
}