开发者

Textarea X/Y caret coordinates - jQuery plugin [duplicate]

This question alre开发者_如何学Pythonady has answers here: How do I get the (x, y) pixel coordinates of the caret in text boxes? (2 answers) Closed 8 years ago.

I'm looking to get the X/Y coordinates of the caret within a textarea on key down. I've searched vigorously but without any luck whatsoever, it seems you can get the position, but not the on-screen X/Y coordinates.


The only viable way of doing this, AFAIK:

  1. Append the contents of the TEXTAREA to a DIV
  2. Append the DIV to the DOM
  3. Place a SPAN inside the DIV at the character offset of the caret.
  4. Take the offset of the SPAN ($(span).offset()...) and minus the offset of the DIV (depending on whether you want the x/y coords relative to the textarea or the page)

Note: When copying the text from the TEXTAREA to the DIV, make sure to copy relevant CSS properties that may affect the offset (width, height, padding, margin, border, font-size, line-height etc.).


I wrote this jQuery plugin for exactly that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜