Get current cursor position in a textbox

后端 未结 2 1758
生来不讨喜
生来不讨喜 2020-11-29 06:28

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:

2条回答
  •  爱一瞬间的悲伤
    2020-11-29 07:03

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

提交回复
热议问题