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

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

    Here is a thought:

    If we can generate the keyborad events just as if the user is typing in the textarea, then browser will automatically be able to handle Undo event. So instead of just appending / changing the value of textarea, we should try to simulate keyboard events for the text that we want to insert.

    As per the documentation at MDN (links given below), we can use KeyboardEvent object to generate the events like:

      var e1 = new KeyboardEvent(, 
    ); var b1 = .dispatchEvent(e1);

    Where:

    • represents the event type such as keydown, keypress or keyup
    • represents the object having event details such key, code
    • represents the target textbox on which we want to trigger the event

    Here is a JSFiddle where I've tried to simulate keydown, keypress and keyup events for each character in a given string. Though its firing the appropriate event handlers, somehow the chars are not getting displayed / added to textbox.

    What I've noticed is that there are some differences in the event object generated when I type a in the textbox verses when I simulate the 3 events for a using my code. The differences are (when tested in Firefox 50.1.0):

    1. explicitOriginalTarget is different than originalTarget when I simulate the events; and when I type in textbox both have same value
    2. rangeParent and rangeOffset values are null / 0 when I type in textbox; and when I simulate the events they have some values
    3. isTrusted property is true when I type in textbox; and when I simulate the events its false (For any event generated using script it will have false)

    MDN links:

    • Creating and triggering built in events
    • KeyboardEvent
    • KeyboardEvent Constructor

提交回复
热议问题