适用于任何类型项目:vue、react、angular、js、ts、jsp、jquery
1、功能封装:
export function useMouseActionTip(text: string, parentEl: HTMLElement, offset?: XY) {function mousemove(e: MouseEvent) {const offsetX = offset?.x || 16;const offsetY = offset?.y || 16;cursorEl.style.left = e.pageX + offsetX + "px";cursorEl.style.top = e.pageY + offsetY + "px";}function mouseenter() {cursorEl.style.display = "block";}function mouseout() {cursorEl.style.display = "none";}const cursorEl = document.createElement("div");cursorEl.className = "_mouse_action_tip";cursorEl.innerHTML = text;cursorEl.style.display = "block";setStyle();document.body.appendChild(cursorEl);document.addEventListener("mousemove", mousemove);parentEl.addEventListener("mouseenter", mouseenter);parentEl.addEventListener("mouseout", mouseout);return {destroy() {document.removeEventListener("mousemove", mousemove);setStyle();parentEl.removeEventListener("mouseenter", mouseenter);parentEl.removeEventListener("mouseout", mouseout);document.body.removeChild(cursorEl);},};
}
export type UseMouseActionTip = ReturnType<typeof useMouseActionTip>;
let hasStyle = false;
function setStyle() {if (hasStyle) {return;}hasStyle = true;const styleElement = document.createElement("style");styleElement.textContent = `._mouse_action_tip {position: fixed;display: flex;padding: 5px 10px;background-color: #33383e;color: #e8eaec;border-radius: 4px;pointer-events: none;z-index: 9999;box-shadow: rgba(255, 255, 255, 0.3) 0px 0px 3px, rgba(255, 255, 255, 0.3) 0px 0px 3px;font-size: 14px;}`;document.head.appendChild(styleElement);
}
2、使用:
let mouseTip: UseMouseActionTip | undefined;
watch(() => editorStore.currentSubTool,() => {if (editorStore.currentSubTool === SubTools.Measure) {mouseTip = useMouseActionTip(t("Editor.Tip.Hold_down_and_drag_the_mouse"),editorStore.canvas().canvas.upperCanvasEl);} else {mouseTip?.destroy();mouseTip = undefined;}}
);