在文本输入字段中获取光标位置(以字符为单位) [英] Get cursor position (in characters) within a text Input field

查看:99
本文介绍了在文本输入字段中获取光标位置(以字符为单位)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从输入字段中获取插入符号位置?



我通过Google找到了一些小部分,但没有任何防弹措施。



基本上,像jQuery插件这样的东西是理想的,所以我可以简单地做

  $(#myinput)。caretPosition()


解决方案

更新更简单:

使用 field.selectionStart 在这个答案中举例



感谢@commonSenseCode指出了这一点。






旧的答案:

。不是基于jquery的,但将它集成到jquery中没有问题:

  / * 
**返回插入符号光标)指定文本字段的位置。
**返回值范围是0-oField.value.length。
* /
函数doGetCaretPosition(oField){

//初始化
var iCaretPos = 0;

// IE支持
if(document.selection){

//设置元素的焦点
oField.focus();

//获取光标位置,得到空的选择范围
var oSel = document.selection.createRange();

//将选择开始位置移动到0位置
oSel.moveStart('character',-oField.value.length);

//插入位置是选择长度
iCaretPos = oSel.text.length;
}

// Firefox支持
else if(oField.selectionStart || oField.selectionStart =='0')
iCaretPos = oField.selectionStart;

//返回结果
返回iCaretPos;
}


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.

Basically something like a jQuery plugin would be ideal, so I could simply do

$("#myinput").caretPosition()

解决方案

Easier update:

Use field.selectionStart example in this answer.

Thanks to @commonSenseCode for pointing this out.


Old answer:

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.
** 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.selectionStart;

  // Return results
  return iCaretPos;
}

这篇关于在文本输入字段中获取光标位置(以字符为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆