JS在指定光标位置处插入内容
知识点:
selectionStart:光标选区开始位置;
selectionEnd:光标选区结束位置
setSelectionRange :设定 或 元素中当前选中文本的起始和结束位置。语法:
element.setSelectionRange(selectionStart, selectionEnd [, selectionDirection]);
参数说明:
如果 selectionEnd 小于 selectionStart,则二者都会被看作 selectionEnd。
selectionStart:被选中的第一个字符的位置索引,从0开始。如果这个值比元素的 value 长度还大,则会被看作 value 最后一个位置的索引。
selectionEnd:被选中的最后一个字符的 下一个 位置索引。如果这个值比元素的value长度还大,则会被看作value最后一个位置的索引。
selectionDirection (可选):一个表示选择方向的字符串,可能的值有:“forward”,“backward”,“none” 默认值,表示方向未知或不相关。
template代码
<a-textarea id="manuscriptTitle" v-model="model.manuscriptTitle" auto-size />
script代码
const manuscriptTitle = document.getElementById('manuscriptTitle')
let strStyle = '{'
strStyle = strStyle + item + '}'
let value = this.$refs.dataTable1.getDetailModal().getFieldValue('manuscriptTitle')
if (
value !== undefined &&
(manuscriptTitle.selectionStart || manuscriptTitle.selectionStart === 0)
) {
const startPos = manuscriptTitle.selectionStart
const endPos = manuscriptTitle.selectionEnd
value = value.substring(0, startPos) + strStyle + value.substring(endPos, value.length)
this.$nextTick()
manuscriptTitle.focus() // 插入完内容再获取焦点
manuscriptTitle.setSelectionRange(endPos + value.length, endPos + value.length)
} else {
value = strStyle
}