光标前面的字符

Characters preceding the cursor

本文关键字:字符 前面 光标      更新时间:2023-09-26

是否可以使用keydown事件将索引检索到光标所在的文本区域?

是的。


textarea.addEventListener('keydown', function (){
    console.log(textarea.selectionEnd); //The position of the cursor. If something is selected, then the position of the end of the selection.
}, false);

此函数在IE中不起作用。在IE中,你必须使用document.createTextRange() .

请参考下面的实现链接。您可以在keydown事件上调用getCaret函数来获取插入符号的索引:

https://stackoverflow.com/a/263796/639960