Many of my friends may be confused about how the pop-up user list function is implemented when they input @ on Sina Weibo and Hujiang broken up.
,
The most difficult problem to solve is to obtain the relative position of the current cursor text box. Because a common <textarea> </textarea> cannot be obtained through normal channels.
What should we do ~
Step 1: Create a normal textarea box, and then set a DIV in the outer layer of textarea (The position of the DIV is set to relative, then the position of the pop-up box will be located based on this Div).
Step 2: Create a div of the same size as textarea (it doesn't matter where the DIV is located). Here I first call it div_textarea.
Note: The font, text size, and line spacing of the DIV must be consistent with those used in the text box. ThenDiv_textareaThe position is also set to relative, and visibility is set to hidden (this is behind the operation, of course it cannot be seen)
Note: This div is used to obtain the relative position of the input @ time mark.
The structure is as follows:
Step 3: Obtain the relative location of the script
Operation: when the user enters @, the script automatically copies the characters in the text boxDiv_textarea, And then obtain the current text box cursor behind the first few words, after obtaining the @ equivalent to the same position of the text box, insert <SPAN class = "nowpos"> </span> (the relative position of the span and @ should be the same ).
After insertion, you only need to get the spanDiv_textareaTo know the location of @ from the text box.
After obtaining the relative position, we can do the following.