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

三世轮回 提交于 2019-11-28 04:53:28

问题


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.


回答1:


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.).




回答2:


I wrote this jQuery plugin for exactly that.



来源:https://stackoverflow.com/questions/3510009/textarea-x-y-caret-coordinates-jquery-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!