我有一个力布局 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/