将键盘事件侦听器添加到svg div容器

时间:2016-08-30 09:33:08

标签: javascript html d3.js svg

我正在尝试将键盘甚至是侦听器(keyup,keydown)添加到包含<div>元素的<svg>This post notes that SVGs do not currently support handling keyboard events,因此我尝试将事件添加到<div>周围的<svg>。但它似乎也没有用。 (fiddle)也没有将事件处理程序添加到SVG中包含的所有元素的组中。

这可能吗?我做错了吗?

(我不想将事件处理程序分配给bodywindow,因为我在页面的不同部分有一个文本输入表单。)

2 个答案:

答案 0 :(得分:3)

您可以将键盘事件附加到svg元素。但随着键盘向下,你必须附加焦点事件而不附加焦点它不起作用。

var chart = d3.select("#chart")
    .style("fill", "red")
    .style("height", '600px')

var svg = chart.append("svg")
    .attr("width", 500)
    .attr("height", 300);

var currentObject = null;

svg.append("circle")
    .attr("class","selectme").attr("id","circle")
    .attr("cx",50).attr("cy",50).attr("r",45)
    .style("fill","lightblue");
svg.append("rect")
    .attr("class","selectme").attr("id","rectangle")
    .attr({"x":10,"y":150,"width":150,"height":100})
    .style("fill","lightgreen");
d3.selectAll(".selectme")
    .on("mouseover", function() {
        d3.select(this).style("stroke","black");
        currentObject = this;
    })
    .on("mouseout", function() {
        d3.select(this).style("stroke","none");
        currentObject = null;
    });

d3.select("svg")
    .on("keydown", function() {
        svg.append("text")
            .attr("x","5")
            .attr("y","130")
            .style("font-size","20px")
        .text("keyCode: " + d3.event.keyCode + " applied to : " + (currentObject===null ? "nothing!" : currentObject.id))  
          .transition().duration(2000)
            .style("font-size","5px")
            .style("fill-opacity",".1")
          .remove();
    }).on("focus", function(){});

答案 1 :(得分:0)

使用值为 tabindex 的属性 0。示例:

<div tabindex="0">...</div>

tabindex=0 使 div 成为可选择的,这样您就可以通过关注它来捕捉关键事件。 根据文档,“ tabindex="0" 表示该元素在顺序键盘导航中应该是可聚焦的”。 (https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex)

另一个信息来源:https://stackoverflow.com/a/3149416/9649530

另一种解决方案是使用 contenteditable="true",但这也会显示您在 div 中键入的键序列。

相关问题