d3:拦截特定元素上的按键事件 [英] d3: intercepting keydown events over specific elements

查看:124
本文介绍了d3:拦截特定元素上的按键事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确定在特定D3元素上发生的按键事件.以下代码段(此处 JSFiddle )可以正确识别各个div上的鼠标以及全局按键事件,但确实似乎没有触发div特定的按键处理程序(到目前为止仅在Chrome上进行了测试).最简单的方法是:

I want to identify key press events which occur over specific D3 elements. The following snippet (JSFiddle here) correctly identifies mousing over individual divs, and global key press events, but does not seem to fire the div-specific key press handler (tested only on Chrome so far). What is the simplest way to either:

  1. 确定光标在哪个div/svg上方,或者
  2. 将密钥处理程序附加到特定的div/svg
  1. identify which div/svg the cursor is over, or
  2. attach a key handler to a specific div/svg

?

_.each(_.range(2), function (i) {
    var svg = d3.select("#plot" + i).append("svg")
        .attr("width", 100)
        .attr("height", 100);

    svg.append("rect")
        .attr("fill", "red")
        .attr("x", 0)
        .attr("y", 0)
        .attr("width", 100)
        .attr("height", 100)
        .on("mouseover", function () { console.log("mouseover", i); })
        .on("keydown", function () { console.log("div key", i); });
});

d3.select("body").on("keydown", function () { console.log("global key"); });

谢谢!

编辑

作为后续,我想我可以在mouseover处理程序中捕获div ID,并使用它在全局keydown事件中标识适当的div,但是我很好奇是否存在更优雅或更惯用的解决方案./p>

As a followup, I suppose I could capture the div ID in the mouseover handler and use that to identify the appropriate div in the global keydown event -- but I'm curious if there is a more elegant or idiomatic solution.

推荐答案

* D'oh.您的编辑正是采用了这种解决方案.是的,这可能是处理它的最佳方法. *

您可能需要使用mouseover处理程序来跟踪当前关注的元素,然后使用页面侦听器将事件委托给该节点.

You might need to use the mouseover handler to keep track of the element that is currently focused, and then use the page listener to delegate the event to that node.

类似这样的东西:

var focused = null;
svg.append("rect").on("mouseover", function () { focused = this; })

然后在页面处理程序中:

And then in your page-handler:

d3.select("body").on("keydown", function () { d3.select(focused); /* then do something with it here */ });

这篇关于d3:拦截特定元素上的按键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆