最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Detecting keypress in D3.js - Stack Overflow

programmeradmin1浏览0评论

I have read many posts and answers, but they all seem to be out of date.

My goal is to be able to "tab" through text and run a function on enter and/or spacebar. I have tried keyCode, charCode, key, which, keypress, keyup, keydown etc...

I have a text node that I can tab through using:

.attr('role', 'button')
.attr('tabindex', '0')
.attr('focusable', 'true')
.on('click', sel)
.on('keypress', function(){if(key == 13 || key == 32){return sel}}) 

The on click is perfect and the tab works, just the function is not called when the space and enter are used.

any help is appreciated.

I have read many posts and answers, but they all seem to be out of date.

My goal is to be able to "tab" through text and run a function on enter and/or spacebar. I have tried keyCode, charCode, key, which, keypress, keyup, keydown etc...

I have a text node that I can tab through using:

.attr('role', 'button')
.attr('tabindex', '0')
.attr('focusable', 'true')
.on('click', sel)
.on('keypress', function(){if(key == 13 || key == 32){return sel}}) 

The on click is perfect and the tab works, just the function is not called when the space and enter are used.

any help is appreciated.

Share Improve this question edited Oct 13, 2017 at 1:04 Gerardo Furtado 102k9 gold badges128 silver badges177 bronze badges asked Oct 12, 2017 at 15:18 BradBrad 871 silver badge6 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

You have to use d3.event.keyCode. According to the API, d3.event...:

... is set during the invocation of an event listener, and is reset after the listener terminates. Use this to access standard event fields.

Here is a basic demo. Click on "foo", "bar" or "baz" to focus, then press any key and look at the console:

var body = d3.select("body");
var p = body.selectAll(null)
  .data(["foo", "bar", "baz"])
  .enter()
  .append("p")
  .attr('tabindex', '0')
  .attr('focusable', 'true')
  .html(String)
  .on("keypress", function() {
    if(d3.event.keyCode === 32 || d3.event.keyCode === 13){
    console.log("Congrats, you pressed enter or space!")
    }
  })
<script src="https://d3js/d3.v4.min.js"></script>

发布评论

评论列表(0)

  1. 暂无评论