[英]How to prevent vertical scroll on swipe left/right
当我尝试向左/向右滑动我的应用程序内容时,也会垂直滚动创建凌乱的用户体验。 有没有办法防止它?
这是我处理滑动的方式
// angular directive
link: function(scope, element, attrs) {
$ionicGesture.on('swiperight', function(){console.log("swiped");}, element );
}
前言:在确保与ios和android环境的兼容性之后,这个解决方案被完全改写了。 以下评论可能不再适用; 欢迎任何反馈。
是的 ,有一种方法可以防止在水平滑动时滚动应用内容:通过将angularjs tapDetector
指令与ionic $ionicScrollDelegate
服务相结合。
我们还需要使用非常快速的dom事件检测来检测滑动( mousedown
/ touchstart
, mousemove
/ touchmove
, mouseup
/ touchend
); 这是必要的,因为$ionicGesture
事件监听器在滚动完成后检测到滑动:为了我们的目的,检测离子滑动是否会减慢。
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提供)
目前离子团队没有API来做这件事,但我暂时做了一个猴子补丁和功能请求。 https://github.com/driftyco/ionic/issues/2703
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.