ionic 手势事件
完整梳理 Ionic 1 全部 15 个声明式触摸手势指令(长按、轻击、双击、触摸、释放、四向拖拽与四向滑动)及 `$ionicGesture.on()`/`off()` 编程式服务 API,并说明现代 Ionic 7/8 `createGesture()` 迁移方案。
学完这一章,你能够
- 完整梳理 Ionic 1 全部 15 个声明式触摸手势指令(长按、轻击、双击、触摸、释放、四向拖拽与四向滑动)及 `$ionicGesture.on()`/`off()` 编程式服务 API,并说明现代 Ionic 7/8 `createGesture()` 迁移方案。
15 个声明式手势指令与触发阈值解析
Ionic 1 内置了一套覆盖移动端常见触摸交互的声明式属性指令,可直接写在 `<button>` 或任意视图元素上:按压与点按类包括 `on-touch`(手指刚接触屏幕即刻触发,不等 `touchend`/`mouseup`)、`on-release`(触摸结束时触发)、`on-tap`(轻击且按住不超过 250ms)、`on-double-tap`(双击)以及 `on-hold`(长按满 500ms 触发);移动类则分为持续跟随手指移动的拖拽系列(`on-drag` 及 `on-drag-up`/`right`/`down`/`left`)与强调高速划动的轻扫系列(`on-swipe` 及 `on-swipe-up`/`right`/`down`/`left`)。下面的速查表完整核对了全部 15 个手势指令及其标准按钮写法。
$ionicGesture 编程式监听服务与现代迁移
除模板指令外,Ionic 1 还通过 `$ionicGesture` 服务向 AngularJS 暴露底层 `ionic.EventController` 手势引擎(注:原参考文中的 `ionicionic.EventController` 属拼写重复)。使用 `$ionicGesture.on(eventType, callback, $element, options)` 可在指令 `link` 函数或控制器中动态为 jqLite/Angular 元素注册手势监听器,并返回代表该绑定的手势句柄对象。
当作用域销毁(`$scope.$on('$destroy', ...)`)或不再需要监听时,应调用 `$ionicGesture.off(...)` 解除绑定以防止内存泄漏。需要提醒工程实践中的一个重要细节:虽然早期参考表将 `off` 写作 `off(eventType, callback, $element)`,但 Ionic 1 源码实际签名为 `$ionicGesture.off(gesture, eventType, callback)`,首个参数应传入 `on()` 返回的手势对象句柄。迁移至现代 Ionic 7/8 时,自定义手势统一通过 `@ionic/core` 的 `createGesture({ el, gestureName, onStart, onMove, onEnd })` 或浏览器原生 Pointer Events 实现,配合 Capacitor 触觉反馈插件可获得原生级手感。
Ionic 1 全部 15 个声明式手势指令速查
| 事件指令 | 触发机制与阈值 | 典型 HTML 用法 | 交互演示核对 |
|---|---|---|---|
| on-hold | 长按持续约 500ms 触发。 | <button on-hold="onHold()" class="button">Test</button> | 离线阈值验证(>=500ms) |
| on-tap | 轻击触发;按住超过 250ms 则不再判定为轻击。 | <button on-tap="onTap()" class="button">Test</button> | 离线阈值验证(<=250ms) |
| on-double-tap | 短时间内连续两次轻击屏幕触发。 | <button on-double-tap="onDoubleTap()" class="button">Test</button> | 离线双击判定验证 |
| on-touch | 手指接触元素立即触发,无需等待 touchend/mouseup。 | <button on-touch="onTouch()" class="button">Test</button> | 离线指令解析验证 |
| on-release | 手指离开屏幕结束触摸时触发。 | <button on-release="onRelease()" class="button">Test</button> | 离线指令解析验证 |
| on-drag | 按住并移动手指时持续触发,类似桌面拖拽。 | <button on-drag="onDrag()" class="button">Test</button> | 离线拖拽方向验证 |
| on-drag-up | 按住并向上拖拽时触发。 | <button on-drag-up="onDragUp()" class="button">Test</button> | 离线向上拖拽验证 |
| on-drag-right | 按住并向右拖拽时触发。 | <button on-drag-right="onDragRight()" class="button">Test</button> | 离线向右拖拽验证 |
| on-drag-down | 按住并向下拖拽时触发。 | <button on-drag-down="onDragDown()" class="button">Test</button> | 离线向下拖拽验证 |
| on-drag-left | 按住并向左拖拽时触发。 | <button on-drag-left="onDragLeft()" class="button">Test</button> | 离线向左拖拽验证 |
| on-swipe | 任意方向的快速手指轻扫滑动触发。 | <button on-swipe="onSwipe()" class="button">Test</button> | 离线轻扫速度验证 |
| on-swipe-up | 向上快速轻扫滑动时触发。 | <button on-swipe-up="onSwipeUp()" class="button">Test</button> | 离线向上轻扫验证 |
| on-swipe-right | 向右快速轻扫滑动时触发。 | <button on-swipe-right="onSwipeRight()" class="button">Test</button> | 离线向右轻扫验证 |
| on-swipe-down | 向下快速轻扫滑动时触发。 | <button on-swipe-down="onSwipeDown()" class="button">Test</button> | 离线向下轻扫验证 |
| on-swipe-left | 向左快速轻扫滑动时触发。 | <button on-swipe-left="onSwipeLeft()" class="button">Test</button> | 离线向左轻扫验证 |
$ionicGesture.on(eventType, callback, $element, options) 参数表
| 参数 | 类型 | 说明 |
|---|---|---|
| eventType | string | 要监听的手势事件名(如 'hold'、'swipeleft')。 |
| callback | function(e) | 手势触发时执行的回调函数,接收事件对象 e。 |
| $element | element | 待绑定监听器的 AngularJS/jqLite 元素。 |
| options | object | 可选配置对象,控制手势识别选项(如阻止默认行为)。 |
$ionicGesture.off() 移除监听参数核对
| 参数 | 类型 | 说明 |
|---|---|---|
| eventType | string | 要移除监听的手势事件名(实际 Ionic 1 签名需首参传入 on() 返回的 gesture 句柄)。 |
| callback | function(e) | 此前注册的同一回调函数引用。 |
| $element | element | 被监听的 AngularJS 元素(对应原表记录,工程中建议使用 on() 返回句柄注销)。 |
运行全部 15 个 Ionic 手势指令解析、按压阈值、四向拖拽/轻扫与 $ionicGesture 注册注销离线实测
"""Offline Ionic 1 gesture directive & $ionicGesture service verifier."""
import json
from lxml import html
GESTURE_DIRECTIVES = [
("on-hold", "onHold()"),
("on-tap", "onTap()"),
("on-double-tap", "onDoubleTap()"),
("on-touch", "onTouch()"),
("on-release", "onRelease()"),
("on-drag", "onDrag()"),
("on-drag-up", "onDragUp()"),
("on-drag-right", "onDragRight()"),
("on-drag-down", "onDragDown()"),
("on-drag-left", "onDragLeft()"),
("on-swipe", "onSwipe()"),
("on-swipe-up", "onSwipeUp()"),
("on-swipe-right", "onSwipeRight()"),
("on-swipe-down", "onSwipeDown()"),
("on-swipe-left", "onSwipeLeft()"),
]
class IonicGestureService:
"""Models $ionicGesture.on / off listener registry."""
def __init__(self):
self._listeners = []
def on(self, event_type, callback, element_id, options=None):
handle = {
"eventType": event_type,
"callback": callback,
"element": element_id,
"options": options or {},
}
self._listeners.append(handle)
return handle
def off(self, gesture_or_type, event_type=None, callback=None):
if isinstance(gesture_or_type, dict):
self._listeners = [h for h in self._listeners if h is not gesture_or_type]
else:
self._listeners = [
h for h in self._listeners
if not (h["eventType"] == gesture_or_type and h["callback"] == event_type)
]
def dispatch(self, element_id, event_type, payload):
fired = []
for h in list(self._listeners):
if h["element"] == element_id and h["eventType"] == event_type:
fired.append(h["callback"](payload))
return fired
def classify_press(duration_ms: int, tap_count: int = 1) -> str:
if tap_count >= 2 and duration_ms <= 250:
return "double-tap"
if duration_ms >= 500:
return "hold"
if duration_ms <= 250:
return "tap"
return "release-only"
def classify_motion(dx: int, dy: int, velocity: float):
if abs(dx) >= abs(dy):
direction = "right" if dx > 0 else "left"
else:
direction = "down" if dy > 0 else "up"
kind = "swipe" if velocity >= 0.6 else "drag"
return [kind, f"{kind}-{direction}"]
def main():
cases = []
# Case 1: Parse all 15 gesture directive button snippets
parsed = {}
for attr, expr in GESTURE_DIRECTIVES:
el = html.fromstring(f'<button {attr}="{expr}" class="button">Test</button>')
parsed[attr] = el.get(attr)
expected_parsed = dict(GESTURE_DIRECTIVES)
cases.append({
"name": "parse_all_15_gesture_directives",
"summary": "解析全部 15 个 Ionic 手势指令(touch/release/tap/hold/drag*/swipe*)",
"expected": expected_parsed,
"actual": parsed,
"passed": parsed == expected_parsed,
})
# Case 2: Press threshold classification (touch -> tap <= 250ms, hold >= 500ms, double-tap)
actual_press = {
"short_120ms": classify_press(120, 1),
"double_100ms": classify_press(100, 2),
"mid_350ms": classify_press(350, 1),
"long_500ms": classify_press(500, 1),
"long_650ms": classify_press(650, 1),
}
expected_press = {
"short_120ms": "tap",
"double_100ms": "double-tap",
"mid_350ms": "release-only",
"long_500ms": "hold",
"long_650ms": "hold",
}
cases.append({
"name": "tap_hold_threshold_rules",
"summary": "验证轻击(<=250ms)、双击与长按(>=500ms)时间阈值判定",
"expected": expected_press,
"actual": actual_press,
"passed": actual_press == expected_press,
})
# Case 3: Drag & swipe directional dispatch across all 4 axes
actual_dir = {
"drag_up": classify_motion(0, -40, 0.2),
"drag_right": classify_motion(50, 5, 0.25),
"drag_down": classify_motion(4, 60, 0.3),
"drag_left": classify_motion(-45, 2, 0.2),
"swipe_up": classify_motion(0, -80, 1.1),
"swipe_right": classify_motion(90, 0, 1.2),
"swipe_down": classify_motion(0, 85, 0.9),
"swipe_left": classify_motion(-95, 5, 1.4),
}
expected_dir = {
"drag_up": ["drag", "drag-up"],
"drag_right": ["drag", "drag-right"],
"drag_down": ["drag", "drag-down"],
"drag_left": ["drag", "drag-left"],
"swipe_up": ["swipe", "swipe-up"],
"swipe_right": ["swipe", "swipe-right"],
"swipe_down": ["swipe", "swipe-down"],
"swipe_left": ["swipe", "swipe-left"],
}
cases.append({
"name": "drag_and_swipe_directions",
"summary": "验证 drag 与 swipe 通用事件及上下左右四方向事件分类",
"expected": expected_dir,
"actual": actual_dir,
"passed": actual_dir == expected_dir,
})
# Case 4: $ionicGesture.on() and off() registration/removal lifecycle
svc = IonicGestureService()
cb = lambda e: f"held:{e['target']}"
gesture_handle = svc.on("hold", cb, "btn-1", {"prevent_default": True})
before_off = svc.dispatch("btn-1", "hold", {"target": "btn-1"})
svc.off(gesture_handle, "hold", cb)
after_off = svc.dispatch("btn-1", "hold", {"target": "btn-1"})
actual_svc = {"before_off": before_off, "after_off": after_off, "remaining": len(svc._listeners)}
expected_svc = {"before_off": ["held:btn-1"], "after_off": [], "remaining": 0}
cases.append({
"name": "ionic_gesture_on_off_service",
"summary": "验证 $ionicGesture.on 注册监听、派发回调与 off 注销清理",
"expected": expected_svc,
"actual": actual_svc,
"passed": actual_svc == expected_svc,
})
print(json.dumps({
"version": "CPython 3.12.14 / lxml offline Ionic JS directive & service verifier",
"cases": cases,
}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 验证 15 个按钮手势属性解析、tap(<=250ms)/hold(>=500ms)/double-tap 判定、drag/swipe 四个方向分派以及 $ionicGesture.on/off 生命周期。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:1bcda2ae0ebe6b893bc40322c2a9b5fd2ede42f70108ce008f2c31f5c4ed96b2
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:4d22f6eacedbfb28040e7a1897eaad52755722d94b4654a2850daaf50ebe139a
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
on-touch 与 on-tap 的触发时机有何区别?on-drag 与 on-swipe 又适用于哪些不同场景?
展开参考解答
on-touch 在手指刚触碰屏幕时立即触发,无需等待抬手;on-tap 需在 250ms 内完成按下并抬手。on-drag 用于跟随手指连续移动(如拖动排序),on-swipe 则用于识别快速单次划动(如卡片切换或左滑删除)。