开发者

Autocomplete popup for textarea

I am trying to build a username autocomplete feature in my webapp so when you type the @ symbol a little popup with an arrow appears point at your @ sign and it filters down as you continue to type the username (and clicking finishes it off).

I can do most of this, however the major part I am struggling with is getting some coordinates in x and y that I can use to position the popover...

For reference here is a JSFiddle Fiddle I am working on.. http://jsfiddle.net/tarnfeld/Xefdb/3/

To get the main functionality working I have a little red span that I'd like to move to the caret position (the little | symbol as your typing) so I can further extend this to be awesome autocomplete love.

Any help would be appreciated :)

Thanks!!

开发者_如何学编程PS: I have found answers like this Twitter-style autocomplete in textarea but they dont pop up under the @ char position...


This seems to be pretty complicated. Basically, you have to get the current character position and convert it to X/Y coordinates.

I found the following links which might help you:

  • Caret position in textarea, in characters from the start
  • Display DIV at Cursor Position in Textarea
  • http://kirblog.idetalk.com/2010/03/calculating-cursor-position-in-textarea.html

Calculating the x/y position is the tricky part. Both solutions (second and third link) create temporary elements (<div> or <textarea>) and fill them succesively with text calculating their height/width.

HTH.


WooHoo!

So, with some reading and hacking I got this working.. You can take a look here (please read the message at the top!) http://jsfiddle.net/Xefdb/9/

I havn't yet tried it in IE so if anyone could and if it doesnt work properly send me a screenshot @tarnfeld that'd be awesome.

Here's a quick intro to how it works:

  • Get the caret position
  • Duplicate the editable wrapper and place it in the same place as the real editable wrapper
  • Wrap the character you just wrote in a span
  • Use jQuery to get the spans absolute position
  • Remove the duplicated wrapper
  • Position the element you wish to track the caret at the x/y of the span you just worked out.

If anyone can find a nicer way to do this please let me know!

PS. It should deal with scrolling too!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜