获取文本输入字段中的光标位置(以字符为单位) [英] Get cursor position (in characters) within a text Input field
本文介绍了获取文本输入字段中的光标位置(以字符为单位)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从输入字段中获取插入符号位置?
How can I get the caret position from within an input field?
我通过谷歌找到了一些零碎的东西,但没有防弹.
I have found a few bits and pieces via Google, but nothing bullet proof.
基本上像 jQuery 插件这样的东西是理想的,所以我可以简单地做
Basically something like a jQuery plugin would be ideal, so I could simply do
$("#myinput").caretPosition()
推荐答案
更容易更新:
在此答案中使用 field.selectionStart
示例.
感谢@commonSenseCode 指出这一点.
Thanks to @commonSenseCode for pointing this out.
旧答案:
找到了这个解决方案.不是基于 jquery,但集成到 jquery 中没有问题:
Found this solution. Not jquery based but there is no problem to integrate it to 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;
}
这篇关于获取文本输入字段中的光标位置(以字符为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文