介绍
在前端研发中我们经常需要使用脚本在文本框中插入内容。如果产品要求不能直接插入开始或者尾部,而是要插入到光标位置,此时我们就需要获取光标/光标选中的位置。
HTML API
HTML中的textarea元素提供了相应的API:textarea文档
selectionStart & selectionEnd
这两个属性分别对应选中区域的开始位置和结束位置,当没有选中任何内容的时候,两个值相等并且值为光标位置。
在光标/选中位置插入内容
const insert = (textAreaElement, content) => {
const curVal = textAreaElement.value
const start = textAreaElement.selectionStart
const end = textAreaElement.selectionEnd
textAreaElement.value = curVal.substring(0, start) + content + curVal.substring(end);
}