javascript - d3.behaviour.zoom 禁用仅使用一根手指时在触摸屏上的平移

标签 javascript d3.js

我有一个力布局 d3 图表,我正在使用 d3.behaviour.zoom启用缩放和平移。

一切都很好,但是因为我的图表填满了 iPad 上的屏幕,所以无法向下滚动页面,因为我的触摸只是平移图表。

我想在触摸设备上保持双指缩放行为。

是否可以取消 touchmove.zoom事件d3.event.touches.length === 1

这只会禁用所有触摸交互 - 所以滚动没问题,但我无法再缩放图表:

selection.call(zoom)
    .on('touchstart.zoom', null)
    .on('touchmove.zoom', null)
    .on('touchend.zoom', null);

我还尝试添加另一个 touchmove听众,像这样:

selection.call(zoom)
    .on('touchmove', function () {
        if (d3.event.touches.length === 1) {
            d3.event.stopPropagation();
            // i've also tried d3.event.preventDefault() but it doesn't do anything         
        }
    });

我认为我无法访问默认缩放 touchmove我可以在 d3 中听众吗?我想知道我是否可以删除 touchstart 上的监听器然后在 touchend 上重新绑定(bind)它如果用户只使用一次触摸。

最佳答案

不使用 d3 dispatch 的一种方法是使用原始的 touchstart 事件监听器而不是 d3。通过 event.touches.length,您可以统计在屏幕上检测到的触摸次数。

通过添加监听器并额外检查触摸计数何时为 1 d3.behaviour.zoom,当一根手指放在图形上时它会阻止平移,并且默认为正常滚动页面。

let touchCount = 0;

// Only necessary to add listener when running on mobile/tablet
// (assuming you already have some detection set up)

if (isMobileSize) {
    document.querySelector('.your-svg').addEventListener('touchstart', (e) => {
        touchCount = e.touches.length;
    });
}


let selection = d3.select('.your-svg');
let zoom = d3.behavior.zoom().on('zoom', () => {

    // When 1 finger, do not zoom
    if (touchCount === 1) {
        d3.event.sourceEvent.stopPropagation();
        return;
    }

    // Otherwise run zoom/move
    // ... zoom logic goes here....
})

selection.call(zoom)

关于javascript - d3.behaviour.zoom 禁用仅使用一根手指时在触摸屏上的平移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35085371/

相关文章:

javascript - 如何使用 jquery 在实际的 div 本身中显示 div 的 html5 "data"标签中保存的信息

svg - d3 轴标签在 chrome 和 firefox 中被切断

javascript - d3.js 液体填充计剪辑路径不工作

javascript - 带 Y 值跟踪的 D3.js 多系列图表

javascript - 在 d3.js 中传播缩放事件

javascript - 在 Three.js 中移动对象

javascript - 在javascript中将树从graphql格式转换为json格式

javascript - 使用node-api将数组缓冲区从C转发到JS

javascript - map API savedata 函数 if 语句被忽略

javascript - 如何从数据中选择 d3.js 中的唯一值