How to listen keyboard events on svg

2019-01-26 18:39发布

问题:

I have a svg and I can draw multiple shapes on this svg. Now my requirement is I want to listen keyboard events like ctrl+C, ctrl+V, ctrl+D, Esc, Delete so that I can copy, paste , duplicate selected shape. But I have no idea about listening keyboard events on SVG . I tried following code but no luck !!

 mySVG.on("keydown", function () {
        //code to handle keydown
  });

Any help ? Thanks in advance.

回答1:

Because SVG is not an input-type, listen for the event on the window instead:

$(window).on('keypress', function (evt){ ... })