【问题标题】:Detecting enter key on a svg element检测 svg 元素上的输入键
【发布时间】:2019-05-31 05:35:44
【问题描述】:

我正在尝试通过仅使用键盘输入进行导航来使我的网站更易于访问。为此,我需要能够对动态创建的 SVG 元素 g 进行制表符,然后按 Enter 打开包含更多信息的模式。

我可以检测到何时按下了任何键,但没有专门输入。我见过很多人描述如何检测输入元素上的输入按键,但这并不能解决我的问题。我遇到的问题是 myEvent 只是一个普通事件而不是键盘事件。所以它没有键码。我还看到它建议使用 myEvent.key 或 myEvent.which,它也没有。所以我不知道如何获取按下了什么键的信息。

我不知道此信息是否有用,但我的网站是一个查看家族历史树的网络应用程序,因此每个 SVG 元素都是树中节点的可视化表示。我正在尝试在每个节点上进行制表符,并在按下回车键时显示有关焦点节点的人的更多信息。

 var g:Element = document.createElementNS("http://www.w3.org/2000/svg", "g");

 g.setAttribute('tabindex', "0"); // So I can tab to the element

 g.addEventListener("keypress",  function (myEvent) {
      // To this point everything works.

      // The next line gives an error.
      if(myEvent.keyCode === 13) { // 13 is enter
           // Open my modal
      }
 });

【问题讨论】:

标签: javascript typescript svg


【解决方案1】:

试着做一个演员表。

var container:Element = document.createElement("div");
var svg:Element = document.createElementNS("http://www.w3.org/2000/svg", "svg");

 var g:Element = document.createElementNS("http://www.w3.org/2000/svg", "g");

 g.setAttribute('tabindex', "0"); // So I can tab to the element

 g.addEventListener("keypress",  function (myEvent:KeyboardEvent) {
      // To this point everything works.
      
     console.log(myEvent);
      // The next line gives an error.
      if(myEvent.keyCode === 13) { // 13 is enter
          alert('enter');
      }
 });

var circle:Element = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circle.setAttribute("cx", "20");
circle.setAttribute("cy", "20");
circle.setAttribute("r", "15");

g.appendChild(circle);
svg.appendChild(g);
container.appendChild(svg);
document.body.appendChild(container);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-02
    • 2018-09-23
    • 2014-04-18
    • 2017-06-20
    • 2015-06-05
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    相关资源
    最近更新 更多