使用方法
let mover;
let offsets;
let position;
function addEvent(type, callback, target = document) {target.addEventListener(type, callback, false);}
function removeEvent(type, callback, target = document) {target.removeEventListener(type, callback);}
function offsetPosition(target) {
let node = target;
let X = 0;
let Y = 0;
do {
X += node.offsetLeft;
Y += node.offsetTop;
node = node.offsetParent;
} while (
node);
return { X, Y };
}
function parentsUntilMatch(target, filter) {
if (!target || target.nodeType === 9) return null;
switch (true) {
case 'matchesSelector' in target:
if (target.matchesSelector(filter)) return target;
break;
case 'mozMatchesSelector' in target:
if (target.mozMatchesSelector(filter)) return target;
break;
case 'msMatchesSelector' in target:
if (target.msMatchesSelector(filter)) return target;
break;
case 'oMatchesSelector' in target:
if (target.oMatchesSelector(filter)) return target;
break;
case 'webkitMatchesSelector' in target:
if (target.webkitMatchesSelector(filter)) return target;
break;
default:
if (target.matches(filter)) return target;
break;}
return parentsUntilMatch(target.parentNode, filter);
}
function styleStringFromObj(obj) {
let str = '';
for (const prop in obj) {
str += `${prop}:${obj[prop]};`;
}
return str;
}
function mousedown(isTouch = false) {
const MOVE = isTouch ? 'touchmove' : 'mousemove';
const END = isTouch ? 'touchend' : 'mouseup';
return function caller(evt) {
const target = parentsUntilMatch(evt.target, '.js-is-draggable');
if (!target) return;
mover = target;
offsets = { X: evt.pageX, Y: evt.pageY };
position = offsetPosition(mover);
mover.setAttribute('style', styleStringFromObj({
position: 'relative',
top: `${position.Y}px`,
left: `${position.X}px` }));
mover.classList.add('js-is-dragging');
mover.setAttribute('aria-grabbed', true);
addEvent(MOVE, mousemove);
addEvent(END, mouseup(isTouch));
};
}
function mousemove(evt) {
// evt.preventDefault();
// new offsets based on mouse position
const newOffsets = {
X: evt.pageX,
Y: evt.pageY };
const newY = position.Y + (newOffsets.Y - offsets.Y);
const newX = position.X + (newOffsets.X - offsets.X);
// update styles
mover.style.top = newY + 'px';
mover.style.left = newX + 'px';
// update object
offsets = newOffsets;
// update position
position = { X: newX, Y: newY };
}
function mouseup(isTouch = false) {
const MOVE = isTouch ? 'touchmove' : 'mousemove';
const END = isTouch ? 'touchend' : 'mouseup';
return function caller(evt) {
removeEvent(MOVE, mousemove);
removeEvent(END, caller);
mover.classList.remove('js-is-dragging');
mover.setAttribute('aria-grabbed', false);
mover = offsets = position = undefined;
};
}
addEvent('mousedown', mousedown());
addEvent('touchstart', mousedown(true));
站长提示:
1. 苦力吧素材官方QQ群:
950875342
2. 平台上所有素材资源,需注册登录会员方能正常下载。
3. 会员用户积极反馈网站、素材资源BUG或错误问题,每次奖励
2K币。
4. PHP源码类素材,如需协助安装调试,或你有二次开发需求,可联系苦力吧客服。
5. 付费素材资源,需充值后方能下载,如有任何疑问可直接联系苦力吧客服