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

后端 未结 12 689
失恋的感觉
失恋的感觉 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:13

    You need to insert the text in a special way so the user can use the normal undo/redo behaviour.

    var textEvent = document.createEvent('TextEvent');
    
    textEvent.initTextEvent('textInput', true, true, null, "new text");
    
    document.getElementById("your-textarea").dispatchEvent(textEvent);
    

提交回复
热议问题