vue实现文本选取
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 增强处理:
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;
}
或通过动态类名:
<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);
}
}






