简体   繁体   English

用SVG文档拦截html中的键盘事件的正确方法是什么?

[英]What's the correct way to intercept keyboard events in html with an SVG document?

I have a html document whose relevant portion for this question is as follows: 我有一个html文档,此问题的相关部分如下:

<body onload='main()'>

<object id='svg' type="image/svg+xml" data="b.svg"></object>

</body>

The function main ( onload = .. ) is used to install an event handler for the keydown event: 函数main( onload = .. )用于为keydown事件安装事件处理程序:

function main() {

  document.addEventListener('keydown', 
       function(ev) { 
         console.log('DOC keydown, ev.keyCode = ' + ev.keyCode); 
        },
       false);
}

This works as intended until I click into the area occupied by b.svg . 直到我单击b.svg占据的区域,此操作b.svg Afterwards, the keyboard events seem somehow to be processed through/within the SVG document and they don't make it to the document object's event handler. 之后,似乎可以通过SVG文档/在SVG文档中以某种方式处理键盘事件,而这些事件不会传递给document对象的事件处理程序。

I can now add another event listener on the SVG element itself: 现在,我可以在SVG元素本身上添加另一个事件侦听器:

  var svg=document.getElementById('svg');
  var svgDoc = svg.contentDocument;

  svgDoc.addEventListener('keydown', 
       function(ev) { 
         console.log('SVG keydown, ev.keyCode = ' + ev.keyCode); 
        },
       false);

Which again does work as intended. 再次按预期工作。

Yet, I feel this is a bit clumsy and inelegant. 但是,我觉得这有点笨拙和笨拙。 If possible, I'd like to have only one event listener. 如果可能的话,我只希望有一个事件监听器。

So, is this the correct way to handle keyboard events in a html page with an SVG drawing, or are there better alternatives? 那么,这是处理带有SVG图纸的html页面中的键盘事件的正确方法,还是有更好的替代方法?

如果您不希望svg处理事件,请在其根元素中添加pointer-events =“ none”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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