HumanBreak/src/plugin/use.ts

63 lines
1.8 KiB
TypeScript
Raw Normal View History

2022-11-14 17:11:23 +08:00
export default function init() {
2022-11-16 23:01:23 +08:00
return { useDrag, useWheel, isMobile };
2022-11-14 17:11:23 +08:00
}
/**
*
* @param ele
* @param fn x y和鼠标事件或点击事件
* @param ondown
* @param global
*/
export function useDrag(
ele: HTMLElement,
fn: (x: number, y: number, e: MouseEvent | TouchEvent) => void,
ondown?: (x: number, y: number, e: MouseEvent | TouchEvent) => void,
global: boolean = false
) {
let down = false;
ele.addEventListener('mousedown', e => {
down = true;
if (ondown) ondown(e.clientX, e.clientY, e);
});
ele.addEventListener('touchstart', e => {
down = true;
if (ondown) ondown(e.touches[0].clientX, e.touches[0].clientY, e);
});
document.addEventListener('mouseup', () => (down = false));
document.addEventListener('touchend', () => (down = false));
const target = global ? document : ele;
target.addEventListener('mousemove', e => {
if (!down) return;
const ee = e as MouseEvent;
fn(ee.clientX, ee.clientY, ee);
});
target.addEventListener('touchmove', e => {
if (!down) return;
const ee = e as TouchEvent;
fn(ee.touches[0].clientX, ee.touches[0].clientY, ee);
});
}
/**
*
* @param ele
* @param fn
*/
export function useWheel(
ele: HTMLElement,
fn: (x: number, y: number, z: number, e: WheelEvent) => void
): void {
ele.addEventListener('wheel', e => {
fn(e.deltaX, e.deltaY, e.deltaZ, e);
});
}
2022-11-16 23:01:23 +08:00
/**
*
*/
export const isMobile = matchMedia('(max-width: 600px)').matches;