Twitter-style autocomplete in textarea

前端 未结 10 1453
情歌与酒
情歌与酒 2020-12-02 06:38

I am looking for a Javascript autocomplete implementation which includes the following:

  • Can be used in a HTML textarea
  • Allows for typing regular text
10条回答
  •  难免孤独
    2020-12-02 07:16

    Recently i had to face this problem and this is how i nailed down...

    1. Get the string index at the cursor position in the textarea by using selectionStart
    2. slice the string from index 0 to the cursor position
    3. Insert it into a span (since span has multiple border boxes)
    4. Get the dimensions of the border box using element.getClientRects() relative to the view port. (here is the MDN Reference)
    5. Calculate the top and left and feed it to the dropdown

    This works in all latest browsers. haven't tested at old ones

    Here is Working bin

提交回复
热议问题