当我尝试向左/向右滑动时,我的应用内容也会垂直滚动,从而造成混乱的用户体验。有没有办法防止它?
这就是我处理滑动的方式
// angular directive
link: function(scope, element, attrs) {
$ionicGesture.on('swiperight', function(){console.log("swiped");}, element );
}
当我尝试向左/向右滑动时,我的应用内容也会垂直滚动,从而造成混乱的用户体验。有没有办法防止它?
这就是我处理滑动的方式
// angular directive
link: function(scope, element, attrs) {
$ionicGesture.on('swiperight', function(){console.log("swiped");}, element );
}
前言:在确保与 ios 和 android 环境兼容后,此解决方案被完全改写;以下评论可能不再适用;欢迎任何反馈。
是的,当您水平滑动时,有一种方法可以防止应用内容滚动:通过将 angularjstapDetector
指令与 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 之间的差值 (delta);
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 测试的
差点忘了:这是一支工作笔(由 sMr 提供)
目前 ionic 团队没有 API 可以做到这一点,但我暂时提出了一个猴子补丁和功能请求。https://github.com/driftyco/ionic/issues/2703