获取文本输入字段中的光标位置(以字符为单位)
2022-08-30 00:17:28
如何从输入字段中获取插入符号位置?
我通过谷歌找到了一些零碎的东西,但没有防弹。
基本上,像jQuery插件这样的东西是理想的,所以我可以简单地做
$("#myinput").caretPosition()
如何从输入字段中获取插入符号位置?
我通过谷歌找到了一些零碎的东西,但没有防弹。
基本上,像jQuery插件这样的东西是理想的,所以我可以简单地做
$("#myinput").caretPosition()
更新更简单:
在此答案中使用示例。field.selectionStart
感谢@commonSenseCode指出这一点。
旧答案:
找到此解决方案。不是基于jquery的,但将其集成到jquery没有问题:
/*
** Returns the caret (cursor) position of the specified text field (oField).
** Return value range is 0-oField.value.length.
*/
function doGetCaretPosition (oField) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange();
// Move selection start to 0 position
oSel.moveStart('character', -oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionDirection=='backward' ? oField.selectionStart : oField.selectionEnd;
// Return results
return iCaretPos;
}
用。它与所有主流浏览器兼容。selectionStart
document.getElementById('foobar').addEventListener('keyup', e => {
console.log('Caret at: ', e.target.selectionStart)
})
<input id="foobar" />
仅当未定义类型或或输入时,此方法才有效。type="text"
type="textarea"