得到一个文本框当前光标位置(Get current cursor position in a tex

2019-08-31 13:25发布

我需要一个代码, 找到一个TextBox / 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>

任何建议?

Answer 1:

它看起来OK除了在你的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 <= 8,你需要注意,这些浏览器不支持selectionStartselectionEnd



Answer 2:

这里有一个可能的方法。

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);
})


文章来源: Get current cursor position in a textbox