当前位置:首页 > VUE

vue实现文字选中

2026-03-30 12:41:52VUE

Vue 实现文字选中功能的方法

使用 window.getSelection() API

通过监听鼠标事件获取用户选中的文本内容,适用于原生 Vue 或组合式 API。

<template>
  <div @mouseup="handleTextSelection">
    <p>选中这段文字试试...</p>
  </div>
</template>

<script>
export default {
  methods: {
    handleTextSelection() {
      const selection = window.getSelection();
      if (selection.toString().length > 0) {
        console.log('选中文本:', selection.toString());
      }
    }
  }
}
</script>

自定义指令封装

创建可复用的指令,自动处理选中逻辑。

vue实现文字选中

Vue.directive('select-text', {
  bind(el, binding) {
    el.addEventListener('mouseup', () => {
      const selectedText = window.getSelection().toString();
      if (selectedText && binding.value) {
        binding.value(selectedText);
      }
    });
  }
});

// 使用方式
<template>
  <div v-select-text="handleSelected">
    <p>指令方式实现的文字选中</p>
  </div>
</template>

高亮选中文本

结合 Range API 实现视觉反馈。

vue实现文字选中

methods: {
  highlightSelection() {
    const range = window.getSelection().getRangeAt(0);
    const span = document.createElement('span');
    span.className = 'highlight';
    range.surroundContents(span);
  }
}

<style>
.highlight {
  background-color: yellow;
}
</style>

组合式 API 实现

适用于 Vue 3 的响应式处理。

import { ref } from 'vue';

export function useTextSelection() {
  const selectedText = ref('');

  const onSelection = () => {
    selectedText.value = window.getSelection().toString();
  };

  return { selectedText, onSelection };
}

// 组件中使用
const { selectedText, onSelection } = useTextSelection();

跨浏览器兼容方案

处理 IE 兼容性问题。

function getSelectedText() {
  if (window.getSelection) {
    return window.getSelection().toString();
  } else if (document.selection) {
    return document.selection.createRange().text;
  }
  return '';
}

注意事项

  • 移动端需要额外处理 touch 事件
  • 长按选择与点击事件可能存在冲突
  • 富文本编辑器场景需使用 contenteditable 相关 API
  • 选中状态可通过 CSS ::selection 伪元素自定义样式

标签: 文字vue
分享给朋友:

相关文章

vue 实现过滤

vue 实现过滤

Vue 实现过滤的方法 在 Vue 中实现过滤功能可以通过多种方式完成,包括使用计算属性、自定义过滤器、第三方库等。以下是几种常见的实现方法: 使用计算属性进行过滤 计算属性是 Vue 中最常用的过…

vue 实现排序

vue 实现排序

Vue 实现排序的方法 使用计算属性实现排序 通过计算属性对数组进行排序,可以保持原始数据不变。示例代码展示了如何对列表按名称升序排序: <template> <div>…

vue实现心电图

vue实现心电图

Vue 实现心电图效果 在 Vue 中实现心电图效果通常需要结合 Canvas 或 SVG 进行动态绘图,模拟心电图数据的实时变化。以下是两种实现方式的核心思路和代码示例: 使用 Canvas 绘制…

vue实现hovuer

vue实现hovuer

Vue 实现 Hover 效果 在 Vue 中实现 hover 效果可以通过多种方式完成,以下是几种常见的方法: 使用 CSS 直接控制 通过 :hover 伪类实现,无需额外的 JavaScrip…

vue实现webshell

vue实现webshell

Vue 实现 WebShell 使用 Vue 实现 WebShell 需要结合前端与后端的交互,通常通过 WebSocket 或 HTTP 协议与服务器通信。以下是一个基于 Vue 和 WebSock…

vue日历实现

vue日历实现

实现基础日历布局 使用Vue的模板语法构建日历的基本HTML结构。一个典型的日历包含星期标题和日期格子,可以通过v-for循环生成。月份切换功能通过计算属性动态更新日期数组。 <templat…