vue3+tsx实现选中文字弹出工具栏的功能

89 阅读1分钟

vue3+tsx实现选中文字弹出工具栏的功能

2151a98fdca54a36b64f5fc356c5bd1f.gif

  1. 首先要捕获鼠标选中文字事件,通过监听mouseup事件,在检测鼠标选中文字的事件 ``
 // 组件挂载时添加事件监听
    onMounted(() => {
      document.addEventListener("mouseup", handleTextSelection);
      document.addEventListener("mousedown", handleClickOutside);
    });
    // 捕获选中文字 处理要显示的位置
    const handleTextSelection = () => {
      // 防抖功能
      if (debounceTimer.value) clearTimeout(debounceTimer.value);
      debounceTimer.value = setTimeout(() => {
        // 捕获选中的文字
        const selection = window.getSelection();
        if (!selection || selection.toString().trim() === "") {
          showTooltip.value = false;
          return;
        }
        // 处理选中的文字
        selectedText.value = selection.toString();
        const range = selection.getRangeAt(0);
        // 获取选中文本的位置
        const rect = range.getBoundingClientRect();
        // 计算工具菜单位置
        let top = rect.top + window.scrollY;
        if (top <= props.height) {
          top = rect.top + props.height + rect.height + 20;
        }
        const left = rect.left + rect.width / 2;
        tooltipPosition.value = { top, left };
        showTooltip.value = true;
      }, 100);
    };
    // 点击页面其他地方关闭工具菜单
    const handleClickOutside = (event: MouseEvent) => {
      const tooltip = document.querySelector(".text-selection-tooltip");
      if (tooltip && !tooltip.contains(event.target as Node)) {
        hideTooltip();
      }
    };
  // 隐藏工具菜单
    const hideTooltip = () => {
      showTooltip.value = false;
      window.getSelection()?.removeAllRanges();
    };

2.封装好之后,只需要传入按钮文字以及icon(图片)就可以了,使用方法:

<TextSelectionTool
    menus={[{title:'复制',icon:'/assets/img/copy.svg'}]}
    onClick={(index, txt) => {
        // index 点击的按钮下标 
        // txt:选中的文字   
   }}
/>

项目地址