javascript - d3 v4 缩放事件未针对鼠标滚轮/触摸屏触发

标签 javascript d3.js svg

我最近迁移到了 D3 v4.10.2。我正在按照文档中的说明调用缩放行为,但是在使用鼠标滚轮或触摸屏缩放时不会执行回调。我正在使用最新版本的 chrome:

 var some_svg = d3.select('body').select("#some-svg");
 var some_svg_rect =  some_svg.append("g").append("rect")
                                          .attr("fill","none")
                                          .attr("width",900)
                                          .attr("height",400);
 some_svg_rect.call(d3.zoom()
                     .on("zoom", function () {/*this code fails to execute*/}));

感谢在将“pointer-events”设置为“all”后缩放工作正常,但是拖动行为仅适用于拖动“start”是否缺少某些东西?:

some_svg_rect.call(d3.drag()
               .on("start", function () {/*this code works*/}) 
               .on("drag", function () {/*this code fails toexecute*/}) 
               .on("end", function () {/*this code fails to execute*/}));

最佳答案

你代码的问题是默认pointer-events对于 SVG,其中:

The element can only be the target of a mouse event when the visibility attribute is set to visible and when the mouse cursor is over the interior (i.e., 'fill') of the element and the fill attribute is set to a value other than 'none', or when the mouse cursor is over the perimeter (i.e., 'stroke') of the element and the stroke attribute is set to a value other than none. (emphasis mine)

但是,我建议您不要将填充设置为transparent(如other answer 中所建议),这通常是个坏主意:尽管有些浏览器支持它,transparent 不是 SVG 规范的一部分。

取而代之的是,只需将指针事件设置为visibleall:

.attr("pointer-events", "all")

这里有一个demo(不要脸抄别人答案的代码)

var some_svg = d3.select('body').select("#some-svg");
var some_svg_rect = some_svg.append("g").append("rect")
  .attr("fill", "none")
  .attr("pointer-events", "all")
  .attr("width", 400)
  .attr("height", 250);
some_svg_rect.call(d3.zoom()
  .on("zoom", function() {
    console.log("zoom works")
  }));
.as-console-wrapper { max-height: 20% !important;}
svg{
  border: 1px solid gray;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg id="some-svg" width=400 height=250></svg>

关于javascript - d3 v4 缩放事件未针对鼠标滚轮/触摸屏触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46247860/

相关文章:

javascript - 根据另一组元素的类不断隐藏不同的元素

algorithm - D3.js 是怎么做到的?

javascript - 以数组作为数据结构的 d3.js 树形布局

javascript - 如何使用 Bobril 将图像添加到 SVG

javascript - MIDI.js 音符持续时间不会改变

javascript - HTML 5 需要验证 .NET Web 表单下拉列表和日期时间选择器

javascript - 鼠标移出事件在 JavaScript D3 中无法正常工作

html - 当 svg 上未指定宽度和高度时,使用 viewbox 和保留纵横比的响应式 svg

html - 无法在 Safari 中渲染 SVG 图像

javascript - 未捕获的范围错误: Callstack exceeded when trying to convert Int8Array to String/JSON