开发者

How to position an element below a text box carret in javascript?

I have a long text field and what I want to do is that when a user types an '@' character a list of users appear just like a typical auto-comple开发者_C百科te. However I want the list of users to appear below the '@' character which could be 20-30 characters in from the start of the text box.

I've found many jQuery auto-complete plugins but none that position the list below the current caret position.

I can get the text field position using $('#textfield').position() and I can get the caret position using something like this but that gets the character index from the text value and not the pixel position.

How can I get the current carret position of a text field relative to the page in pixels in order to position an element below it?


relaying on this anwsear: Calculate text width with JavaScript

what you can do is have a div on the screen which is visible:hidden then every time a new charecter has been entered to the textbox change the inner html of the div

so the textbox value and the div innerhtml will always be synced.

then when you want to popup your autocomplete you will add the width of the div. to the offset left postion of the textbox.

and thats it...

and avcorse you will need that the div and the textbox will have the same font...


This jQuery plugin does what you're after:

http://plugins.jquery.com/project/caretPosition

I haven't tested it, but going by the code it looks like it creates a temporary <span> with the same content as your <textarea> (up to the cursor) and makes wild assumptions about font, line height, whitespace and word wrapping when measuring it.

You could try extending it to:

  1. Copy the font, line height, whitespace and word wrap styles from the target <textarea>

  2. Hide the temporary <span> without affecting the measurement by wrapping it in a <div style="height: 0; overflow: hidden;"> or positioning it absolute -9999px, -9999px


$(this).position().top ;
$(this).position().left ;
$(this).position().right ; etc... :-)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜