Inserting a text where cursor is using Javascript/jquery

前端 未结 13 2665
盖世英雄少女心
盖世英雄少女心 2020-11-22 03:58

I have a page with a lot of textboxes. When someone clicks a link, i want a word or two to be inserted where the cursor is, or appended to the textbox which has the focus.<

13条回答
  •  遇见更好的自我
    2020-11-22 04:19

    Content Editable, HTML or any other DOM element Selections

    If you are trying to insert at caret on a

    , this becomes much more difficult, especially if there are children within the editable container.

    I have had really great luck using the Rangy library:

    • GIT: https://github.com/timdown/rangy
    • NPM: https://www.npmjs.com/package/rangy

    It has a ton of great features such as:

    • Save Position or Selection
    • Then later, Restore the Position or Selection
    • Get selection HTML or Plaintext
    • Among many others

    The online demo was not working last I checked, however the repo has working demos. To get started, simple download the Repo from Git or NPM, then open ./rangy/demos/index.html

    It makes working with caret pos and text selection a breeze!

提交回复
热议问题