我最近迁移到了 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 规范的一部分。
取而代之的是,只需将指针事件设置为visible
或all
:
.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/