Inserting a text where cursor is using Javascript/jquery

前端 未结 13 2673
盖世英雄少女心
盖世英雄少女心 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:35

    Adding text to current cursor position involves two steps:

    1. Adding the text at the current cursor position
    2. Updating the current cursor position

    Demo: https://codepen.io/anon/pen/qZXmgN

    Tested in Chrome 48, Firefox 45, IE 11 and Edge 25

    JS:

    function addTextAtCaret(textAreaId, text) {
        var textArea = document.getElementById(textAreaId);
        var cursorPosition = textArea.selectionStart;
        addTextAtCursorPosition(textArea, cursorPosition, text);
        updateCursorPosition(cursorPosition, text, textArea);
    }
    function addTextAtCursorPosition(textArea, cursorPosition, text) {
        var front = (textArea.value).substring(0, cursorPosition);
        var back = (textArea.value).substring(cursorPosition, textArea.value.length);
        textArea.value = front + text + back;
    }
    function updateCursorPosition(cursorPosition, text, textArea) {
        cursorPosition = cursorPosition + text.length;
        textArea.selectionStart = cursorPosition;
        textArea.selectionEnd = cursorPosition;
        textArea.focus();    
    }
    

    HTML:

提交回复
热议问题