简体   繁体   中英

How to listen keyboard events on svg

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.

由于SVG不是输入类型,因此请在窗口上侦听事件:

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

Add tabindex="0" attribute to the <svg> and it will work:

 const svgElement = document.querySelector('svg'); svgElement.addEventListener('keydown', event => { console.log('svg keydown: ', event.key); });
 <svg tabindex="0" width="300" height="200"> <rect width="100%" height="100%" fill="#555" /> <text x="50%" y="50%" font-size="20" text-anchor="middle" fill="white"> Click me and start typing </text> </svg>

The tabindex attribute allows you to control whether an element is focusable, and...

See MDN docs for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM