ionic 滚动条
系统讲解 Ionic 1 滚动生态三大模块:`<ion-scroll>` 自定义滚动/双指缩放容器、`<ion-infinite-scroll>` 触底分页无限加载与 `ng-if` 终止机制,以及 `$ionicScrollDelegate` 编程控制(`resize`/`scrollTop`/`scrollBottom`/`$getByHandle`),并对照 Ionic 7/8。
学完这一章,你能够
- 系统讲解 Ionic 1 滚动生态三大模块:`<ion-scroll>` 自定义滚动/双指缩放容器、`<ion-infinite-scroll>` 触底分页无限加载与 `ng-if` 终止机制,以及 `$ionicScrollDelegate` 编程控制(`resize`/`scrollTop`/`scrollBottom`/`$getByHandle`),并对照 Ionic 7/8。
ion-scroll 可滚动容器与双指缩放 API
`<ion-scroll>` 用于在页面局部区域创建独立可滚动容器,支持 `direction`(`'x'`、`'y'` 或 `'xy'`,默认 `'y'`)、`paging`(分页吸附滚动)、`scrollbar-x`/`scrollbar-y`(默认隐藏水平条、显示垂直条)、`on-refresh`/`on-scroll` 回调、`delegate-handle` 句柄,以及双指缩放三联属性 `zooming`、`min-zoom`(默认 `0.5`)与 `max-zoom`(默认 `3`)。
地图画布示例通过 `<ion-scroll zooming="true" direction="xy" style="width: 500px; height: 500px">` 包裹一块 `5000px x 5000px` 的大图内容块,无需额外控制器代码即可支持任意方向平移与双指缩放(CSS 仅设定桌面光标,JS 仅注册模块 `['ionic']`)。
ion-infinite-scroll 触底无限加载与终止守卫
`<ion-infinite-scroll>` 放置在 `<ion-content>` 或 `<ion-scroll>` 底部:当用户滚动至距底部不超过 `distance`(默认 `'1%'`)阈值时自动触发 `on-infinite` 表达式加载下一页数据,加载期间显示 `icon` 图标(默认 `'ion-loading-d'`)。异步请求完成后务必执行 `$scope.$broadcast('scroll.infiniteScrollComplete')` 告知容器释放加载锁;当后端已无更多数据时,应配合 `ng-if="moreDataCanBeLoaded()"` 将指令从 DOM 移除,彻底停止后续触底请求。
$ionicScrollDelegate 编程控制与现代迁移
`$ionicScrollDelegate` 统一管理 `<ion-content>` 与 `<ion-scroll>` 实例:直接调用服务方法会作用于页面全部滚动视图,调用 `$ionicScrollDelegate.$getByHandle('handle')` 则只针对指定句柄生效。常用方法包括 `resize()`(内容高度动态变化后重新计算滚动边界)、`scrollTop([shouldAnimate])` 与 `scrollBottom([shouldAnimate])`(滚至顶部或底部,可选平滑动画)。迁移至现代 Ionic 7/8 时,页面滚动与滚顶/滚底由 `<ion-content>` 的 `scrollToTop(duration)`、`scrollToBottom(duration)` 承担,无限滚动则使用 `<ion-infinite-scroll>` + `<ion-infinite-scroll-content>` 监听 `ionInfinite` 事件并调用 `event.target.complete()` 与设置 `disabled`。
ion-scroll 属性 API
| 属性 | 类型 | 详情 |
| delegate-handle (可选) | 字符串 | 配合 $ionicScrollDelegate.$getByHandle() 定位特定滚动视图的句柄。 |
| direction (可选) | 字符串 | 滚动方向:'x'、'y' 或 'xy',默认 'y'。 |
| paging (可选) | 布尔值 | 是否开启按页吸附滚动。 |
| on-refresh (可选) | 表达式 | 由内部 ion-refresher 触发的下拉刷新回调表达式。 |
| on-scroll (可选) | 表达式 | 用户滚动容器时触发的回调表达式。 |
| scrollbar-x (可选) | 布尔值 | 是否显示水平滚动条,默认 false。 |
| scrollbar-y (可选) | 布尔值 | 是否显示垂直滚动条,默认 true。 |
| zooming (可选) | 布尔值 | 是否启用双指捏合缩放。 |
| min-zoom (可选) | 数值 | 允许的最小缩放倍率,默认 0.5(注:源表标注为“整数”,实际支持小数如 0.5)。 |
| max-zoom (可选) | 数值 | 允许的最大缩放倍率,默认 3。 |
ion-infinite-scroll 属性 API
| 属性 | 类型 | 详情 |
| on-infinite | 表达式 | 滚动进入底部阈值区间时触发的数据加载表达式。 |
| distance (可选) | 字符串 | 距离底部多远时触发 on-infinite,支持百分比或像素,默认 '1%'。 |
| icon (可选) | 字符串 | 加载过程中显示的图标类名,默认 'ion-loading-d'。 |
$ionicScrollDelegate.scrollTop([shouldAnimate]) 参数表
| 参数 | 类型 | 详情 |
| shouldAnimate (可选) | 布尔值 | 滚动回顶部时是否启用平滑过渡动画。 |
$ionicScrollDelegate.scrollBottom([shouldAnimate]) 参数表
| 参数 | 类型 | 详情 |
| shouldAnimate (可选) | 布尔值 | 滚动到底部时是否启用平滑过渡动画。 |
运行 ion-scroll 缩放边界、ion-infinite-scroll 分页与 $ionicScrollDelegate 离线实测
展开查看收起
"""Offline Ionic 1 ion-scroll, ion-infinite-scroll & $ionicScrollDelegate verifier."""
import json
from lxml import html
class ScrollView:
"""Models an ion-scroll / ion-content viewport controlled by $ionicScrollDelegate."""
def __init__(self, handle, content_height=2000, viewport_height=500, direction="y",
zooming=False, min_zoom=0.5, max_zoom=3.0):
self.handle = handle
self.content_height = content_height
self.viewport_height = viewport_height
self.direction = direction
self.zooming = zooming
self.min_zoom = min_zoom
self.max_zoom = max_zoom
self.zoom_level = 1.0
self.scroll_y = 0
self.resize_calls = 0
self.last_animated = None
def resize(self, new_content_height=None):
self.resize_calls += 1
if new_content_height is not None:
self.content_height = new_content_height
def scroll_top(self, should_animate=False):
self.scroll_y = 0
self.last_animated = bool(should_animate)
def scroll_bottom(self, should_animate=False):
self.scroll_y = max(0, self.content_height - self.viewport_height)
self.last_animated = bool(should_animate)
def zoom_to(self, factor):
if not self.zooming:
return self.zoom_level
self.zoom_level = max(self.min_zoom, min(self.max_zoom, float(factor)))
return self.zoom_level
class IonicScrollDelegate:
def __init__(self, views):
self.views = {v.handle: v for v in views}
def get_by_handle(self, handle):
return self.views[handle]
def scroll_top(self, should_animate=False):
for v in self.views.values():
v.scroll_top(should_animate)
def main():
cases = []
# Case 1: Parse ion-scroll with zooming/direction/min-zoom/max-zoom & ion-infinite-scroll
markup = """
<div>
<ion-scroll delegate-handle="mapScroll" zooming="true" direction="xy"
min-zoom="0.5" max-zoom="3" scrollbar-x="false" scrollbar-y="true"
paging="false" on-scroll="onScroll()" on-refresh="doRefresh()"
style="width: 500px; height: 500px">
<div style="width: 5000px; height: 5000px;"></div>
</ion-scroll>
<ion-content>
<ion-infinite-scroll ng-if="moreDataCanBeLoaded()" icon="ion-loading-c"
on-infinite="loadMoreData()" distance="1%">
</ion-infinite-scroll>
</ion-content>
</div>
"""
doc = html.fromstring(markup)
sc = doc.xpath("//ion-scroll")[0]
inf = doc.xpath("//ion-infinite-scroll")[0]
actual_dom = {
"handle": sc.get("delegate-handle"),
"direction": sc.get("direction"),
"zooming": sc.get("zooming") == "true",
"min_zoom": float(sc.get("min-zoom")),
"max_zoom": float(sc.get("max-zoom")),
"scrollbar_x": sc.get("scrollbar-x") == "true",
"scrollbar_y": sc.get("scrollbar-y") == "true",
"inf_ng_if": inf.get("ng-if"),
"inf_icon": inf.get("icon"),
"inf_distance": inf.get("distance"),
"inf_expr": inf.get("on-infinite"),
}
expected_dom = {
"handle": "mapScroll",
"direction": "xy",
"zooming": True,
"min_zoom": 0.5,
"max_zoom": 3.0,
"scrollbar_x": False,
"scrollbar_y": True,
"inf_ng_if": "moreDataCanBeLoaded()",
"inf_icon": "ion-loading-c",
"inf_distance": "1%",
"inf_expr": "loadMoreData()",
}
cases.append({
"name": "parse_scroll_and_infinite_directives",
"summary": "解析 ion-scroll 全量属性及 ion-infinite-scroll 的 ng-if/distance/icon",
"expected": expected_dom,
"actual": actual_dom,
"passed": actual_dom == expected_dom,
})
# Case 2: Zoom clamping [min-zoom=0.5, max-zoom=3.0]
map_view = ScrollView("mapScroll", 5000, 500, direction="xy", zooming=True, min_zoom=0.5, max_zoom=3.0)
actual_zoom = {
"under_min": map_view.zoom_to(0.1),
"within_range": map_view.zoom_to(2.0),
"over_max": map_view.zoom_to(5.5),
}
expected_zoom = {"under_min": 0.5, "within_range": 2.0, "over_max": 3.0}
cases.append({
"name": "scroll_zoom_clamping",
"summary": "验证 ion-scroll 双指缩放比例受 min-zoom(0.5) 与 max-zoom(3.0) 边界约束",
"expected": expected_zoom,
"actual": actual_zoom,
"passed": actual_zoom == expected_zoom,
})
# Case 3: ion-infinite-scroll pagination with 1% threshold, scroll.infiniteScrollComplete & ng-if stop
pages = [[1, 2], [3, 4]]
loaded = []
broadcasts = []
has_more = True
def try_infinite(scroll_y, content_h, view_h, distance_pct=1.0):
nonlocal has_more
if not has_more:
return False
remaining = content_h - (scroll_y + view_h)
threshold = content_h * (distance_pct / 100.0)
if remaining <= threshold:
if pages:
loaded.extend(pages.pop(0))
if not pages:
has_more = False
broadcasts.append("scroll.infiniteScrollComplete")
return True
return False
t1 = try_infinite(100, 1000, 500) # remaining 400 > 10 -> not triggered
t2 = try_infinite(495, 1000, 500) # remaining 5 <= 10 -> page 1
t3 = try_infinite(995, 1500, 500) # remaining 5 <= 15 -> page 2, has_more becomes False
t4 = try_infinite(1495, 2000, 500) # ng-if false -> blocked
actual_inf = {
"triggers": [t1, t2, t3, t4],
"loaded": loaded,
"has_more": has_more,
"broadcast_count": len(broadcasts),
}
expected_inf = {
"triggers": [False, True, True, False],
"loaded": [1, 2, 3, 4],
"has_more": False,
"broadcast_count": 2,
}
cases.append({
"name": "infinite_scroll_pagination_and_guard",
"summary": "验证 ion-infinite-scroll 的 1% 触底阈值、广播完成事件与 ng-if 终止",
"expected": expected_inf,
"actual": actual_inf,
"passed": actual_inf == expected_inf,
})
# Case 4: $ionicScrollDelegate resize(), scrollBottom(true), scrollTop(true) & $getByHandle
list_view = ScrollView("mainList", content_height=1800, viewport_height=600)
delegate = IonicScrollDelegate([map_view, list_view])
v = delegate.get_by_handle("mainList")
v.resize(2400)
v.scroll_bottom(should_animate=True)
y_bottom = v.scroll_y
anim_bottom = v.last_animated
delegate.scroll_top(should_animate=False)
actual_del = {
"resize_calls": v.resize_calls,
"y_bottom": y_bottom,
"anim_bottom": anim_bottom,
"y_top": v.scroll_y,
"anim_top": v.last_animated,
}
expected_del = {
"resize_calls": 1,
"y_bottom": 1800,
"anim_bottom": True,
"y_top": 0,
"anim_top": False,
}
cases.append({
"name": "scroll_delegate_controls",
"summary": "验证 $ionicScrollDelegate 的 $getByHandle、resize、scrollBottom 与 scrollTop",
"expected": expected_del,
"actual": actual_del,
"passed": actual_del == expected_del,
})
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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
仅隐藏样式不会注销底层滚动监听,用户继续滑到底部仍会反复触发 on-infinite;用 ng-if='moreDataCanBeLoaded()' 变为 false 后会直接销毁指令实例,彻底停止无效分页请求。