script
const formData = ref{
content: '各分公司資產(chǎn)管理崗:\n 根據(jù)《通知》每月報(bào)送相關(guān)信息的要求,現(xiàn)將報(bào)送{{數(shù)據(jù)期間}}營業(yè)職場情況通知如下:\n 一、時(shí)間要求:請務(wù)必于{{填報(bào)截止日期}}前報(bào)送并核對完畢。過時(shí)將關(guān)閉系統(tǒng),無法修改...'
}
const myContent = document.querySelector('#myContent')
// 選擇方法
const selectContent = (event) => {
if (timer) {
clearTimeout(timer)
timer = null
}
const selectionStart = event.target.selectionStart
const selectionEnd = event.target.selectionEnd
let text = formData.value.content
const regex = /\{{([^}]+)\}}/g
const matches = [...text.matchAll(regex)]
const results = matches.map(i => ({
content: i[0],
startIndex: i.index,
endIndex: i.index + i[0].length
}))
for (let i of results) {
if (selectionStart === selectionEnd) {
if (selectionStart >= i.startIndex && selectionEnd <= i.endIndex) {
// 當(dāng)光標(biāo)處于變量詞組內(nèi)部,選中整個詞組
timer = setTimeout(() => {
myContent.setSelectionRange(i.startIndex, i.endIndex)
// 處理鍵盤向左向右切換
if (event.code === 'ArrowLeft' && selectionStart === i.startIndex) {
myContent.setSelectionRange(i.startIndex - 1, i.startIndex - 1)
} else if (event.code === 'ArrowRight' && selectionEnd === i.endIndex) {
myContent.setSelectionRange(i.endIndex + 1, i.endIndex + 1)
}
}, 200)
}
} else if ((selectionStart >= i.startIndex && selectionStart <= i.endIndex) || (selectionEnd >= i.startIndex && selectionEnd <= i.endIndex)) {
// 當(dāng)光標(biāo)處于變量詞組內(nèi)部,選中整個詞組
timer = setTimeout(() => {
myContent.setSelectionRange(i.startIndex, i.endIndex)
}, 200)
}
}
}
// 插入變量
const insertText = async (myValue) => {
if (myContent.selectionStart || myContent.selectionStart === 0) {
const startPos = myContent.selectionStart
const endPos = myContent.selectionEnd
formData.value.content = myContent.value.substring(0, startPos) + myValue + myContent.value.substring(endPos, myContent.value.length)
await nextTick() // 這里是重點(diǎn)
myContent.setSelectionRange(endPos + myValue.length, endPos + myValue.length)
} else {
formData.value.content += myValue
}
}
template
<a-textarea v-model:value="formData.content" id="myContent" autoSize @keyup="selectContent" @click="selectContent" />
<a-button @click="insertText('{{數(shù)據(jù)期間}}')">插入變量</a-button>
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。