怎样完成一个元素的拖拽结果,运用原生的js完成,习惯了jquery的同学们,你们本身写了吗?N久运用mvvm框架,不写jquery的东西,觉得本身完整不会了。
话不多说,直接上code。本例子以简朴的div为例子。
html
<div id="div">我是一个能够退拽的div</div>
css
div {
position: fixed;
left: 0;
top: 0;
width: 100px;
height: 100px;
background: #999;
padding: 10px;
cursor: pointer;
}
javascript
window.onload = funtion() {
const div = document.getElementById('div');
let initPosition = {};
div.addEventListener('mousedown', onMousedown);
function onMousedown(event) {
const { pageX, pageY } = event;
initPosition = getPosition();
document.addEventListener('mousemove', omMousemove);
document.addEventListener('mouseup', onMouseUp);
}
function omMousemove(event) {
const { pageX, pageY } = event;
const { left, top} = calcPosition(pageX, pageY);
div.style.cssText = `left:${left}px;top:${top}px;`;
}
function onMouseUp(event) {
document.removeEventListener('mousemove', onMouseMove);
}
function calcPosition(pageX, pageY) {
const { left, top, scrollLeft, maxCriticalX, maxCriticalY } = initPosition;
let x = pageX - left;
let y = pageY - top;
if (x <= scrollLeft) {
x = scrollLeft;
}
if (x >= maxCriticalX) {
x = maxCriticalX;
}
if (y >= maxCriticalY) {
y = maxCriticalY;
}
if ( y<=0 || maxCriticalY < 0) {
y = 0;
}
return {
left: x,
top: y
};
}
function getPosition() {
const { left, top, width, height } = div.getBoundingClientRect();
const { scrollLeft, scrollTop } = document.body;
const maxCriticalX = scrollLeft + innerWidth - width;
const maxCriticalY = scrollTop + innerHeight - height;
return {
left,
top,
scrollLeft,
maxCriticalX,
maxCriticalY
};
}
};