[英]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.我有一个 svg,我可以在这个 svg 上绘制多个形状。现在我的要求是我想监听 ctrl+C、ctrl+V、ctrl+D、Esc、Delete 等键盘事件,以便我可以复制、粘贴、复制所选内容形状。 But I have no idea about listening keyboard events on SVG. I tried following code but no luck !!但我不知道在 SVG 上监听键盘事件。我尝试了以下代码但没有成功!
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:将tabindex="0"
属性添加到<svg>
,它将起作用:
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... tabindex 属性允许您控制元素是否可聚焦,以及...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.