开发者

Capture ctr-z(undo) and ctr-y(redo) with JavaScript and perform custom function

I have been writing a sort of online spreadsheet application for a specific purpose and along with it I have written my own undo and redo functions. When the user presses ctr-z or ctr-y the undoes or redoe开发者_C百科s the last changes to the text fields. Is their a way using JavaScript to effectively hijack the ctr-z and ctr-y keypress events that occur anywhere on the page and cause them to run my own functions. Or at a minimum to disable the standard browser functionality.

I need to get this working the recent versions of Firefox and Chrome on windows only.


Using jQuery:

$(document).keydown(function (keyEvent) {
   var keyCode = keyEvent.keyCode;
   if (keyEvent.metaKey === true || keyEvent.ctrlKey === true) {
      if (keyCode === 89) {
         //fire your custom redo logic
         keyEvent.preventDefault();
         return false;
      } 
      else if (keyCode === 90) {
         //special case (CTRL-SHIFT-Z) does a redo (on a mac for example)
         if (keyEvent.shiftKey === true) {
            //fire your custom redo logic
         }
         else {
            //fire your custom undo logic
         }
         keyEvent.preventDefault();
         return false;
      }
   } 
});

This should handle all keyboard based events. It will not handle what happens if the user clicks undo in the menu bar or right clicks and selects undo.


you may put on your page hidden textarea, bind onclick mouse event to function, which will set focus to the textarea, bind the keyboard events of this textarea and if an event is keydown and key is z or y and modifyer is ctrl - then invoke your redo/undo action.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜