当前位置:首页 > VUE

vue实现文本选取

2026-02-17 11:18:01VUE

Vue 实现文本选取的方法

使用原生 JavaScript 事件

通过 @mouseup@touchend 事件监听用户操作,结合 window.getSelection() 获取选中文本。在 Vue 模板中添加事件监听:

<template>
  <div @mouseup="handleTextSelection">
    {{ content }}
  </div>
</template>

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

自定义指令封装

创建 Vue 指令 v-selection 实现复用:

Vue.directive('selection', {
  bind(el, binding) {
    el.addEventListener('mouseup', () => {
      const selection = window.getSelection();
      if (selection.toString().length > 0) {
        binding.value(selection.toString());
      }
    });
  }
});

使用指令:

<div v-selection="handleSelectedText">
  {{ longTextContent }}
</div>

处理跨元素选中

当文本跨越多行或多元素时,需要使用 Range API 增强处理:

vue实现文本选取

methods: {
  getSelectedText() {
    const selection = window.getSelection();
    if (selection.rangeCount > 0) {
      const range = selection.getRangeAt(0);
      return {
        text: range.toString(),
        startOffset: range.startOffset,
        endOffset: range.endOffset
      };
    }
    return null;
  }
}

选中文本高亮显示

结合 CSS 类实现视觉反馈:

::selection {
  background-color: #b3d4fc;
  color: #000;
}

或通过动态类名:

vue实现文本选取

<span :class="{ 'highlight': isSelected(textChunk) }">
  {{ textChunk }}
</span>

第三方库方案

使用专门库如 vue-highlight-text

import VueHighlightText from 'vue-highlight-text';

Vue.use(VueHighlightText);

模板使用:

<vue-highlight-text 
  :queries="highlightTerms"
  :text="fullText"
  @selection="handleSelection"
/>

移动端兼容处理

添加触摸事件支持:

mounted() {
  this.$el.addEventListener('touchend', this.handleTouchSelection);
},
methods: {
  handleTouchSelection() {
    setTimeout(() => {
      const selection = window.getSelection();
      // 处理选中结果
    }, 100);
  }
}

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

相关文章

验证码实现vue

验证码实现vue

验证码实现(Vue) 使用组件库(如Element UI) Element UI提供了现成的验证码组件,可直接集成到Vue项目中。 安装Element UI: npm install elemen…

vue实现单页面

vue实现单页面

Vue 实现单页面应用(SPA) Vue.js 是一个渐进式框架,非常适合构建单页面应用(SPA)。SPA 的核心特点是整个应用只有一个 HTML 页面,通过动态加载内容实现页面切换,无需重新加载整个…

vue插槽实现

vue插槽实现

插槽的基本概念 Vue插槽(Slot)是一种内容分发机制,允许父组件向子组件传递模板片段,子组件通过<slot>标签定义接收位置。插槽的核心作用是增强组件的灵活性和复用性。 默认插槽 子…

vue代理实现

vue代理实现

Vue 代理实现方法 在 Vue 项目中,配置代理可以解决开发环境下的跨域问题,通常通过修改 vue.config.js 文件实现。以下是几种常见的代理配置方式: 基础代理配置 在 vue.conf…

vue 动画实现

vue 动画实现

Vue 动画实现方式 Vue 提供了多种方式实现动画效果,主要分为内置组件和第三方库集成。 使用 Vue 内置过渡组件 Vue 的 <transition> 和 <transiti…

vue实现伸缩

vue实现伸缩

Vue实现伸缩功能的方法 使用CSS过渡和Vue的v-if或v-show 通过CSS的transition属性结合Vue的条件渲染指令(v-if或v-show)可以实现元素的伸缩效果。定义一个CSS类…