vue实现文字选中
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 兼容性问题。

function getSelectedText() {
if (window.getSelection) {
return window.getSelection().toString();
} else if (document.selection) {
return document.selection.createRange().text;
}
return '';
}
注意事项
- 移动端需要额外处理
touch事件 - 长按选择与点击事件可能存在冲突
- 富文本编辑器场景需使用
contenteditable相关 API - 选中状态可通过 CSS
::selection伪元素自定义样式






