获取文本框中的当前光标位置

时间:2013-04-19 13:13:16

标签: javascript firefox textbox cursor

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

<!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>

有什么建议吗?

2 个答案:

答案 0 :(得分:37)

除了您的ID属性中的空格(它无效)以及您在检查选择之前替换输入值之外,它看起来还不错。

function textbox()
{
        var ctl = document.getElementById('Javascript_example');
        var startPos = ctl.selectionStart;
        var endPos = ctl.selectionEnd;
        alert(startPos + ", " + endPos);
}
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">

此外,如果您支持IE&lt; = 8,则需要注意这些浏览器不支持selectionStartselectionEnd

答案 1 :(得分:5)

这是一种可能的方法。

function isMouseInBox(e) {
  var textbox = document.getElementById('textbox');

  // Box position & sizes
  var boxX = textbox.offsetLeft;
  var boxY = textbox.offsetTop;
  var boxWidth = textbox.offsetWidth;
  var boxHeight = textbox.offsetHeight;

  // Mouse position comes from the 'mousemove' event
  var mouseX = e.pageX;
  var mouseY = e.pageY;
  if(mouseX>=boxX && mouseX<=boxX+boxWidth) {
    if(mouseY>=boxY && mouseY<=boxY+boxHeight){
       // Mouse is in the box
       return true;
    }
  }
}

document.addEventListener('mousemove', function(e){
    isMouseInBox(e);
})