光标位置设置
const targetDom = document.querySelector('#expressionInput textarea')
setCaretPosition (targetDom, startPos) {
// 光标设置 targetDom:元素(input/textarea),startPos:位置num
const el = targetDom
let range
if (el.setSelectionRange) {
el.focus()
el.setSelectionRange(startPos, startPos)
} else {
range = el.createTextRange()
range.collapse(true)
range.moveEnd('character', startPos)
range.moveStart('character', startPos)//结束的位置
range.collapse(false)
range.select()
}
}
注意:如果是在vue项目中,textarea绑定参数,则this.$nextTick(() => this.setCaretPosition(targetDom, targetDomPos))