【问题标题】:SVG tag mousedown event with D3带有 D3 的 SVG 标记 mousedown 事件
【发布时间】:2021-06-02 12:52:26
【问题描述】:

我有一个 <svg></svg> 节点,我尝试添加 mousedown 事件,由于某种原因根本没有被触发,而 click 工作正常,这种行为是有意的,svg 标签不能有mousedown 事件附加或我做错了什么?

我正在使用 d3.js 库附加事件:

 d3.select(svg)
    .on("mousedown", (event) => setRectPoint(event, gContainer))
    .on("mousemove", (event) => drawRectOutline(event, gContainer));

【问题讨论】:

  • 您是否将任何 D3 事件绑定到您的 SVG?你使用 D3 V6 吗?
  • 是的,我正在使用 d3 v6,除了在帖子中提到它之外,我不绑定任何其他事件
  • (event) => setRectPoint(event, gContainer) 替换为event => console.log(event)... 你在控制台中看到什么了吗?

标签: javascript svg d3.js event-handling dom-events


【解决方案1】:

如果svg已经是一个选择,你不需要再做d3.select

您可以在下面看到mousedown 在按下鼠标按钮时触发,click 在释放按钮时触发。

const svg = d3.select("#viz")
  .append("svg")
  .attr("width", 240)
  .attr("height", 180);

const drawRect = (e) => {
  d3.select(e.target)
    .append("rect")
    .attr("x", e.x)
    .attr("y", e.y)
    .attr("width", 40)
    .attr("height", 20);
}

const drawCircle = (e) => {
  d3.select(e.target)
    .append("circle")
    .attr("cx", e.x)
    .attr("cy", e.y)
    .attr("r", 20);
}

svg
  .on("mousedown", e => drawRect(e))
  .on("click", e => drawCircle(e));
svg {
  border: 1px solid black;
}

rect {
  fill: #f00;
}

circle {
  fill: #0f0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.7.0/d3.min.js"></script>
<div id="viz"></div>

【讨论】:

  • 在我的情况下它没有成功,因为 react 和 d3.js 的奇怪交互(sry 忘了提及它),所以如果你不考虑这一点,这是正确的方法做吧
猜你喜欢
  • 2015-12-15
  • 1970-01-01
  • 1970-01-01
  • 2019-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多