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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16105482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:16:46  来源:igfitidea点击:

Get current cursor position in a textbox

javascriptfirefoxtextboxcursor

提问by Perseus

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:

我需要一个代码来在 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>

Any suggestion?

有什么建议吗?

回答by Tim Down

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.

除了您的 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()">

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

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

回答by Evan Shortiss

Here's one possible method.

这是一种可能的方法。

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