/**
*
* @param {*} el
* @example <div v-drag></div>
* @example <div v-drag="[1,2,3,4]"></div> 上 右 下 左 边界
*/
export const drag = (el, binding) => {
el.style.position = "fixed!important";
let startX, startY, touchX, touchY;
const elWidth = el.offsetWidth;
const elHeight = el.offsetHeight;
const limit = binding.value || [0, 0, 0, 0];
el.ontouchstart = e => {
// e.preventDefault();
startY = el.offsetTop;
startX = el.offsetLeft;
touchX = e.touches[0].clientX;
touchY = e.touches[0].clientY;
}
el.ontouchmove = e => {
const currTouchX = e.touches[0].clientX;
const currTouchY = e.touches[0].clientY;
e.cancelBubble = true;
const posL = currTouchX - touchX + startX;
const posT = currTouchY - touchY + startY;
const posR = posL + elWidth;
const posB = posT + elHeight;
if (posL >= limit[3] && posR <= (document.documentElement.clientWidth - limit[1])) {
el.style.left = (currTouchX - touchX + startX) + 'px';
}
if (posT >= limit[0] && posB <= (document.documentElement.clientHeight - limit[2])) {
el.style.top = (currTouchY - touchY + startY) + 'px';
}
e.preventDefault();
}
}
网友评论