在文本框中获取当前光标位置 [英] Get current cursor position in a textbox

查看:303
本文介绍了在文本框中获取当前光标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个代码来查找光标在文本框/ textarea中的当前位置。它应该使用chrome和firefox。下面是我使用的代码:

I need a code to find current position of cursor in a textbox/textarea. It should work with chrome and firefox. Following is the code which I am using:

<!DOCTYPE html>
<html>
  <head>
    <script>
      function textbox()
      {
        document.getElementById('Javascript_example').value = document.activeElement.id;
        var ctl = document.getElementById('Javascript_example');
        alert(ctl);

        var startPos = ctl.selectionStart;
        alert(startPos);
        var endPos = ctl.selectionEnd;
        alert(endPos);
      }
    </script>
  </head>
  <body>

    <input id="Javascript_example" name="one" type="text" value="Javascript_example" onclick="textbox()">

  </body>
</html>

有任何建议吗?

推荐答案

除了您的ID属性中的空格(这是无效的),以及您在检查选择之前要替换输入值的事实外,它看起来确定。

It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you're replacing the value of your input before checking the selection.

<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">

JavaScript:

JavaScript:

function textbox()
{
    var ctl = document.getElementById('Javascript_example');
    var startPos = ctl.selectionStart;
    var endPos = ctl.selectionEnd;
    alert(startPos + ", " + endPos);
}

此外,如果您支持IE< = 8,意识到这些浏览器不支持 selectionStart selectionEnd

Also, if you're supporting IE <= 8 you need to be aware that those browsers do not support selectionStart and selectionEnd.

这篇关于在文本框中获取当前光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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