简体   繁体   English

使用javascript在文本区域中当前x,y坐标的光标

[英]current x,y coordinates of cursor in text area using javascript

How can i get current x & y position of my CURSOR within a text area using javascript. 如何使用javascript在文本区域中获取CURSOR的当前x&y位置。 The event is a Keyup event, not a mouse event. 该事件是Keyup事件,而不是鼠标事件。

I am not looking for the current cursor position in terms of charecter but x , y coordinates. 我不是在charecter而是x,y坐标方面寻找当前光标位置。

The only somewhat reliable method I can think of is this: 我能想到的唯一可靠的方法是:

  1. Create a <span> offscreen (absolutely positioned way to the left) 创建一个<span>屏幕外(绝对定位在左侧)
  2. Give it the same font characteristics as the input element. 赋予它与input元素相同的字体特征。
  3. Continuously populate it with the text from the input element but before the caret 使用输入元素中的文本在插入符号之前连续填充它
  4. Use a javascript library to find the pixel width of the offscreen span 使用javascript库查找屏幕外跨度的像素宽度
  5. Use that to determine where the caret is relative to the left side of the input element. 用它来确定插入符号相对于输入元素左侧的位置。

Give it a shot, I'd love to hear how it turns out. 试一试,我很想知道结果如何。

Give this a shot: 试一试:

 $(document).ready(function(){
    $('textarea').bind('keyup', function(e){
      var $this = $(this);
      alert('X: ' + $this.data('mousepos').x + '\nY: ' + $this.data('mousepos').y);
    });

    $('textarea').bind('mousemove', function(e){
      $(e.target).data('mousepos', {x: e.pageX, y: e.pageY});
    });
 });​

workin example: http://jsbin.com/ibowa3/edit workin example: http//jsbin.com/ibowa3/edit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM