输入框的@paste事件操作粘贴复制,选中的内容
例如图上这样,获取我们鼠标选中的内容,输入框
<template>
<div>
<input type="text" v-model="inputText" @paste="handlePaste" />
</div>
</template>
<script>
export default {
data() {
return {
inputText: ""
};
},
methods: {
handlePaste(event) {
// 获取输入框的选中文本范围
const selectionStart = event.target.selectionStart;
const selectionEnd = event.target.selectionEnd;
// 判断文本是否被选中
if (selectionStart !== selectionEnd) {
// 去除选中的内容
this.inputText = this.inputText.slice(0, selectionStart) + this.inputText.slice(selectionEnd);
// 将光标移动到选中文本的起始位置
event.target.setSelectionRange(selectionStart, selectionStart);
console.log("Text is selected. Removed selected text.");
} else {
console.log("Text is not selected. Perform paste operation.");
}
}
}
};
</script>
根据handlePaste事件来获取我们选中的开始下标和结束下标,再通过slice来更改我们输入框中的内容,小编使用这个的起因是因为之前做的input的输入框和文本框交互,对数据操作有个粘贴功能互斥了,粘贴的时候选中再粘贴会直接加在后面,所以需要把选中的截取再进行数据操作。
感兴趣的可以看我之前的文章!实现输入框input与文本框textarea的联动输入,批量查询数据vue+ts_vue文本框联动-CSDN博客