当前位置:首页 > 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.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 实现视觉反馈。

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 兼容性问题。

vue实现文字选中

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 项目中创建一个登录组件,通常命名为 Login.vue。该组件包含表单元素,如用户名和密码输入框,以及提交按钮。 <template&…

vue实现详情

vue实现详情

Vue 实现详情页的常见方法 使用动态路由 在 Vue Router 中配置动态路由参数,通过 $route.params 获取详情 ID。示例路由配置: { path: '/detail/:i…

vue compile 实现

vue compile 实现

Vue 编译实现原理 Vue 的编译过程将模板字符串转换为渲染函数,主要分为解析、优化和代码生成三个阶段。 解析阶段(Parse) 将模板字符串转换为抽象语法树(AST)。Vue 使用正则表达式和有…

vue 实现表单

vue 实现表单

Vue 表单实现方法 Vue.js 提供了多种方式实现表单,包括双向数据绑定、表单验证和动态表单生成。以下是常见的实现方法: 基础表单绑定 使用 v-model 指令实现表单元素与数据的双向绑定:…

利用vue 实现

利用vue 实现

以下是利用 Vue 实现常见功能的几种方法,分为不同场景和技术要点: 数据绑定与响应式更新 Vue 的核心特性是数据绑定,通过 v-model 实现双向绑定: <template>…

vue 实现fadeout

vue 实现fadeout

Vue 实现淡出效果 在 Vue 中实现淡出(fade-out)效果可以通过 CSS 过渡或动画结合 Vue 的动态渲染功能完成。以下是几种常见方法: 使用 Vue 过渡(Transition)组件…