How can I “undo” the programmatic insertion of text into a textarea?

后端 未结 12 690
失恋的感觉
失恋的感觉 2020-12-17 09:27

I have a textarea and a button. Clicking the button causes text to be inserted into the textarea.

Is there a way to allow a user to press Ctrl/Cmd+z to undo the inse

12条回答
  •  情书的邮戳
    2020-12-17 10:15

    Here's a short and non-jQuery solution which works in Firefox too (undo isn't possible in any way there)

    // Solution
    function insertText(textarea, text) {
    	// https://stackoverflow.com/a/55174581/288906
    	if (!document.execCommand('insertText', false, text)) {
    		textarea.setRangeText(text);
    	}
    }
    
    // Demo code to add text on click
    const textarea = document.querySelector('textarea');
    textarea.onclick = () => insertText(
      textarea,
      '@'
    );

    I also packaged this up as an npm module, improving consistency across browsers.

提交回复
热议问题