如何在文本框中获得插入符号的(x,y)像素坐标? [英] How do I get the (x, y) pixel coordinates of the caret in text boxes?

查看:188
本文介绍了如何在文本框中获得插入符号的(x,y)像素坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery,并试图找到一个跨浏览器的方式来获得< textarea> s和输入中插入符号的像素坐标

I am using jQuery and trying to find a cross browser way to get the pixel coordinates of the caret in <textarea>s and input boxes such that I can place an absolutely positioned div around this location.

是否有一些jQuery插件?

Is there some jQuery plugin? Or JavaScript snippet to do just that?

推荐答案

我已经为 meteor-autocomplete ,所以我已经评估了所有的8插件在GitHub。胜利者是目前为止组件 textarea-caret-position / strong>。

I've looked for a textarea caret coordinates plugin for meteor-autocomplete, so I've evaluated all the 8 plugins on GitHub. The winner is, by far, textarea-caret-position from Component.


  • 像素精确度

  • 浏览器兼容性:Chrome,Safari,Firefox(尽管两个 错误有),IE9 +;

  • 可支持任何字体系列和大小,以及文本转换


  • 支持硬返回,制表符(除IE之外)和连续空格

  • 正确位置在长度超过文本区域中的列的位置

  • ghost在空行中的位置在包含长字的行的末尾

  • pixel precision
  • no dependencies whatsoever
  • browser compatibility: Chrome, Safari, Firefox (despite two bugs it has), IE9+; may work but not tested in Opera, IE8 or older
  • supports any font family and size, as well as text-transforms
  • the text area can have arbitrary padding or borders
  • not confused by horizontal or vertical scrollbars in the textarea
  • supports hard returns, tabs (except on IE) and consecutive spaces in the text
  • correct position on lines longer than the columns in the text area
  • no "ghost" position in the empty space at the end of a line when wrapping long words

镜子< div> 在屏幕外创建,样式与< textarea> 完全相同。然后,直到插入符的文本区域的文本被复制到div中,并且紧接着插入< span> 。然后,跨度的文本内容设置为textarea中的文本的其余部分,以便忠实地再现人造div中的包装。

A mirror <div> is created off-screen and styled exactly like the <textarea>. Then, the text of the textarea up to the caret is copied into the div and a <span> is inserted right after it. Then, the text content of the span is set to the remainder of the text in the textarea, in order to faithfully reproduce the wrapping in the faux div.

这是只有方法保证处理所有涉及包裹长行的边缘情况。 GitHub还使用它来确定其 @ 用户下拉菜单的位置。

This is the only method guaranteed to handle all the edge cases pertaining to wrapping long lines. It's also used by GitHub to determine the position of its @ user dropdown.

这篇关于如何在文本框中获得插入符号的(x,y)像素坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆