我正在使用Angular 2和Ionic 2,尝试捕获左右滑动动作。我可以捕获滑动动作,但不知道如何确定它是向左还是向右滑动。
在我的HTML中,我有:
<ion-content (swipe)="swipeEvent($event)">
每次发生滑动时,这会调用swipeEvent
。
我的swipeEvent
JavaScript 代码如下:
swipeEvent(event){
alert('swipe');
}
我如何确定它是左滑还是右滑。
我正在使用Angular 2和Ionic 2,尝试捕获左右滑动动作。我可以捕获滑动动作,但不知道如何确定它是向左还是向右滑动。
在我的HTML中,我有:
<ion-content (swipe)="swipeEvent($event)">
每次发生滑动时,这会调用swipeEvent
。
我的swipeEvent
JavaScript 代码如下:
swipeEvent(event){
alert('swipe');
}
我如何确定它是左滑还是右滑。
当您触发滑动事件时,会向绑定的方法传递一个对象,其中包含一个选项您可以针对特定手势来触发特定功能。构建在Hammer.js之上......
e.direction
,它是与滑动方向相对应的数字值。 Name Value
DIRECTION_NONE 1
DIRECTION_LEFT 2
DIRECTION_RIGHT 4
DIRECTION_UP 8
DIRECTION_DOWN 16
DIRECTION_HORIZONTAL 6
DIRECTION_VERTICAL 24
DIRECTION_ALL 30
例子
假设您的ion-content
设置如下
swipeEvent(e) {
if (e.direction == 2) {
//direction 2 = right to left swipe.
}
}
实用提示
另外(看起来Ionic在他们的手势文档中没有涉及这个),您可以使用HammerJS事件在HTML标记中针对特定的滑动方向进行操作。
<ion-content (swipeleft)="swipeLeftEvent($event)">
只有通过不断试错才发现这个方法,而且似乎对大多数事件都起作用!
html
<ion-navbar *navbar>
<ion-title>Main</ion-title>
</ion-navbar>
<ion-content padding class="main">
// height: 300px; background-color: #000; => visible for test
<div (pan)='swipeEvent($event)'></div>
</ion-content>
typescrip
export class MainPage {
constructor(public nav: NavController) { }
swipeEvent($e) {
// swipe left $e.direction = 2;
// pan for get fired position
console.log($e.deltaX+", "+$e.deltaY);
}
}
如果 deltaX > 0 则向右滑动,否则向左滑动。
我喜欢使用 pan
而不是 swipe
,因为我想制作一个与 Scrollyeah 相同的幻灯片。
<ion-content on-swipe-left="onSwipeLeft()" on-swipe-right="onSwipeRight()">
你也可以使用 on-swipe
,例如:
<ion-content on-swipe="swiped($event)">
$scope.swiped = function($e) {
var what = '';
switch ($e.gesture.direction) {
case 'up':
what = 'Swiped up';
break;
case 'down':
what = 'Swiped down';
break;
case 'left':
what = 'Swiped left';
break;
case 'right':
what = 'Swiped right';
break;
default:
what = 'Swiped ???';
break;
}
alert(what)
}
使用Ionic 2
<ion-content (swipe)="swipeEvent($event)">
swipeEvent($e) {
var what = '';
switch ($e.gesture.direction) {
case 'up':
what = 'Swiped up';
break;
case 'down':
what = 'Swiped down';
break;
case 'left':
what = 'Swiped left';
break;
case 'right':
what = 'Swiped right';
break;
default:
what = 'Swiped ???';
break;
}
alert(what)
}
仅供更新 - 截至Ionic 3.19.0,功能如下:
<div (swipe)="swipeEvent($event)" />
并且
swipeEvent($e) {
if($e.offsetDirection == 4){
// Swiped right, for example:
this.week.prevWeek();
} else if($e.offsetDirection == 2){
// Swiped left, for example:
this.week.nextWeek();
}
}
此外 - 如果您只关心左右滑动,还有一种更快的内联解决方案:
<div (swipe)="($event.direction === 4) ? calendar.back() : calendar.forward()" />
npm install hammerjs
命令,然后进入main.ts
文件并添加一行代码import 'hammerjs';
,这样就可以加载HammerJS库,以便使用滑动事件方法。 - Grant