d3.behavior.zoom 禁用双击

d3.behavior.zoom disable double tap

我不确定这是否可行,但我想禁用双击时的缩放行为,并在平板电脑上使用时保持双指缩放行为。我想将此事件用于其他功能。 如果我禁用 "touchstart.zoom" 事件,我将失去整个缩放功能。

D3 控制您选择使用 d3.behavior.zoom()() 缩放的元素上的 touchstart.zoom 事件。您不能简单地替换此处理程序并有条件地调用原始 D3 处理程序,因为它的部分算法会添加和删除此处理程序,因此您的覆盖将被覆盖。

但是,您可以在更上游捕获此事件并有条件地允许它传播到具有缩放行为的元素。为此,您需要将处理程序添加到子元素,以便它会冒泡到缩放元素。例如:

<g class="zoom_area">  <-- Element you called D3 zoom behaviour on
  <rect width=... height=... style="visibility:hidden; pointer-events:all" class="background">
    // Background rect that will catch all touch events missed by your elements
  </rect>
  <g class="content"> <-- Container for your elements
    ...  <-- Your SVG content
  </g>
</g>

设置正常的 D3 缩放行为:

var zoomer = d3.behavior.zoom();
zoomer(d3.select('g.zoom_area'));

然后设置双触覆盖:

var last_touch_time = undefined;
var touchstart = function() {
    var touch_time = d3.eent.timeStamp;
    if (touch_time-last_touch_time < 500 and d3.event.touches.length===1) {
        d3.event.stopPropagation();
        last_touch_time = undefined;
    }
    last_touch_time = touch_time;
};
d3.select('.background_rect').on('touchstart.zoom', touchstart);
d3.select('.content').on('touchstart.zoom', touchstart);

这是一个替代版本,它只会检测在类似位置发生点击的快速触摸。缺点是在不同位置快速点击仍然会 zoom-in。好处是快速合法的 panning/zooming 手势仍然有效。

var last_touch_event = undefined;
var touchstart = function() {
    if (last_touch_event && d3.event.touches.length===1 &&
        d3.event.timeStamp - last_touch_event.timeStamp < 500 &&
        Math.abs(d3.event.touches[0].screenX-last_touch_event.touches[0].screenX) < 10 &&
        Math.abs(d3.event.touches[0].screenY-last_touch_event.touches[0].screenY) < 10) {
        d3.event.stopPropagation();
        last_touch_time = undefined;
    }
    last_touch_event = d3.event;
};
d3.select('.background_rect').on('touchstart.zoom', touchstart);
d3.select('.content').on('touchstart.zoom', touchstart);