需求描述
在 PC 端编辑短信内容,可以插入人员姓氏以及链接。插入位置随机,完成编辑之后保存确认发送短信。
核心技术点
setSelectionRange 方法用于设定<input> 或 <textarea> 元素中当前选中文本的起始和结束位置。
每次调用这个这个方法都会更新 HTMLInputElement 的 selectionStart, selectionEnd 和 selectionDirection 属性。
// 失去焦点时保存光标位置
campaignNameBlur(e) {
this.cursorPosition = e.srcElement.selectionStart
},
判断内容插入的位置:
// 插入内容
insertVal(val) {
let num = this.cursorPosition
let type = typeof num
let cont = this.content
if (type == "number") {//插入到指定光标处
let right = cont.slice(0, num)
let left = cont.slice(num)
this.content = right + val + left
} else {//没有指定插入直接添加到最后
this.content += val;
}
},
完整代码展示
<template>
<div>
<div class="links">
<p v-for="(item,index) in propList" :key="index" @click="insertVal(item.code )">{{ item.code }}</p>
</div>
<el-input @blur="campaignNameBlur" type="textarea" maxlength="400" show-word-limit :autosize="{ minRows: 4, maxRows: 10 }"
v-model="content">
</el-input>
</div>
</template>
<script>
export default {
data() {
return {
cursorPosition:"",//保存光标位置
content: '', // 短信内容
propList: [
{valuie: "{ famiyname }", code: "#插入姓氏#"},
{valuie: "{ link }", code: "#插入链接#"}
],
}
},
methods: {
// 失去焦点时保存光标位置
campaignNameBlur(e) {
this.cursorPosition = e.srcElement.selectionStart
},
// 插入内容
insertVal(val) {
let num = this.cursorPosition
let type = typeof num
let cont = this.content
if (type == "number") {//插入到指定光标处
let right = cont.slice(0, num)
let left = cont.slice(num)
this.content = right + val + left
} else {//没有指定插入直接添加到最后
this.content += val;
}
},
}
}
</script>