How to obtain the relative position of the cursor in textarea

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.