appending text in textarea with hotkeys and javascript

孤街醉人 提交于 2021-02-11 17:01:22

问题


I have 4 input text tags and 4 textarea tags and I need to create some hotkey like Ctrl+n, Ctrl+r and Ctrl+o to append predefined words at the cursor position for all text fields.

I got this script but is only for onclick event, so I want just to show just one time for the user the text (Press Ctrl+n for word1, Ctrl+r for word2 and Ctrl+o for word3) then he can insert those words every time he is typing some text whatever the field he is.

    <script>
    function addText(event) {
    var targ = event.target || event.srcElement;
    document.getElementById("txt1").value += targ.textContent || targ.innerText;
    }
    </script>
    <div onclick="addText(event)">word1</div>
    <div onclick="addText(event)">word2</div>
    <div onclick="addText(event)">word3</div>

        <label><b>Text 1: </b></label><br>
        <textarea rows="20" cols="80" id = "txt1" name="txt1"></textarea>

        <label><b>Text2: </b></label>
        <input type="text" size="69" name="txt2" value="">

回答1:


You can use something like this.
Please note that I've used underused keys on purpose since certain control key combinations are reserved for browser usage only and cannot be intercepted by the client side JavaScript in the web page (like ctrl+N or ctrl+T).

const arrKey = ['a', 'l', 'b'],
  arrVal = ['addedA', 'addedL', 'addedB'];

function addText(event) {
  if (event.target.classList.contains("addtext")) {
    const index = arrKey.indexOf(event.key);
    if (event.ctrlKey && index != -1) {
      event.preventDefault();
      insertAtCaret(event.target, arrVal[index]);
    }
  }
}

function insertAtCaret(el, text) {
  const caretPos = el.selectionStart,
    textAreaTxt = el.value,
    newCaretPos = caretPos + text.length;

  el.value = textAreaTxt.substring(0, caretPos) + text + textAreaTxt.substring(caretPos);
  el.setSelectionRange(newCaretPos, newCaretPos);
};

document.addEventListener('keydown', addText);
<label><b>Text 1: </b></label><br>
<textarea placeholder="Try ctrl+a or ctrl+b" rows="10" cols="40" id="txt1" name="txt1" class="addtext"></textarea><br/>
<label><b>Text 2: </b></label><br/>
<input type="text" size="40" name="txt2" class="addtext" value=""><br/>
<label><b>Text 3: </b></label><br>
<textarea rows="10" cols="40" id="txt3" name="txt1" class="addtext"></textarea><br/>
<label><b>Text 4: </b></label><br/>
<input type="text" size="40" name="txt4" class="addtext" value="">


来源:https://stackoverflow.com/questions/60908168/appending-text-in-textarea-with-hotkeys-and-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!