/*** 函数防抖(目标时间段内,目标函数只执行最后一次)* @param {*} func 目标函数* @param {*} wait 目标时间段* @param {*} immediate 是否立即执行一次* @returns*/function useDebounce(func, wait, immediate) {let timer;return function() {let context = this;let args = arguments;if (timer) clearTimeout(timer);if (immediate) {var callNow = !timer;timer = setTimeout(() => {timer = null;}, wait);if (callNow) func.apply(context, args);} else {timer = setTimeout(function() {func.apply(context, args);}, wait);}};}
/*** 事件区分处理(左键、右键、双击)* 解决与鼠标拖拽冲突* @param {*} 支持左键、右键、双击事件* @returns 清理函数*/function useEvents(dom, { leftClick, rightClick, dblClick }) {let dblclick = false;let prevPageX = 0;let prevPageY = 0;function handle(event) {if (event.type === 'mousedown') {prevPageX = event.pageX;prevPageY = event.pageY;return;} else if (event.type === 'dblclick') {dblclick = true;setTimeout(() => (dblclick = false), 300);dblClick && dblClick(event);} else {if (prevPageX !== event.pageX || prevPageY !== event.pageY) {return;}if (event.button === 2) {rightClick && rightClick(event);} else {if (dblclick) return;leftClick && leftClick(event);}}}const _handle = useDebounce(handle, 300, false); //函数防抖,消除高频率操作下的重复事件dom.addEventListener('dblclick', handle, false);dom.addEventListener('mousedown', handle, false);dom.addEventListener('mouseup', _handle, false);return () => {dom.removeEventListener('dblclick', handle, false);dom.removeEventListener('mousedown', handle, false);dom.removeEventListener('mouseup', _handle, false);};}
javascript event click/dblclick left/right区分左键 右键 双击事件 排除点击事件与拖拽事件冲突 做防抖优化