前言:在确保与 ios 和 android 环境兼容后,此解决方案被完全改写;以下 cmets 可能不再适用;欢迎任何反馈。
是的,当您水平滑动时,有一种方法可以防止应用内容滚动:通过将 angularjs tapDetector 指令与 ionic $ionicScrollDelegate 服务结合使用。
我们还需要使用非常快速的 dom 事件检测来检测滑动(mousedown/touchstart、mousemove/touchmove、mouseup/touchend);
这是必要的,因为$ionicGesture 事件侦听器会在滚动完成后检测到滑动:在 ionic 中检测滑动是为了减慢我们的目的。
tapDetector 指令被放置在 body 上,如下所示:
<body ng-controller="MyCtrl" tap-detector>
这是指令的代码:
.directive('tapDetector',function($ionicGesture,$ionicScrollDelegate){
return{
restrict:'EA',
link:function(scope,element){
var startX,startY,isDown=false;
element.bind("mousedown touchstart", function(e){
e=(e.touches)?e.touches[0]:e;//e.touches[0] is for ios
startX = e.clientX;
startY = e.clientY;
isDown=true;
//console.log("mousedown",startX,startY);
});
element.bind("mousemove touchmove", function(e){
e=(e.touches)?e.touches[0]:e;//e.touches[0] is for ios
if(isDown){
var deltaX = Math.abs(e.clientX - startX);
var deltaY = Math.abs(e.clientY - startY);
if(deltaX > deltaY) {
//console.log("horizontal move");
$ionicScrollDelegate.$getByHandle('mainScroll').freezeScroll(true);
}
}
});
element.bind("mouseup touchend", function(e){
isDown=false;
$ionicScrollDelegate.$getByHandle('mainScroll').freezeScroll(false);
//console.log("mouseup touchend");
});
}
}
})
当你触摸屏幕(准备滑动)时,触摸的坐标被设置(startX,startY)并且isDown被设置为true。
当您开始滑动时,我们需要确定滑动是水平还是垂直。我们只对水平滑动感兴趣:
var deltaX = Math.abs(e.clientX - startX);
var deltaY = Math.abs(e.clientY - startY);
deltaX 是原始 X 和当前 X 之间的差异(增量);
deltaY 是原始 Y 和当前 Y 的差值(delta);
if (deltaX > deltaY)
我们有一个水平滑动!
现在已经足够快地检测到滑动,剩下要做的就是动态阻止滚动:
$ionicScrollDelegate.$getByHandle('mainScroll').freezeScroll(true);
在 HTML 中:<ion-content delegate-handle="mainScroll">
滚动完成后,我们必须解冻(解冻?)滚动:
element.bind("mouseup touchend", function(e){
isDown=false;
$ionicScrollDelegate.$getByHandle('mainScroll').freezeScroll(false);
});
这是在 iPad 2 上测试的
和 Android Galaxy S4
差点忘了:这是working pen(由 sMr 提供)