Affix 固钉
当内容滚动到指定位置时把它固定在窗口或滚动容器中,适合保持工具条可见。
何时使用
- 长页面中的操作工具条、筛选栏需要在滚动后保持可见。
- 页面在一个独立 ScrollBox 中滚动时,可用
Target固定在该容器内。 - 只需要一个可滚动侧栏或固定顶部布局时,优先用 Layout 布局。
- 页面目录与章节跳转使用 Anchor 锚点。
在线体验
基本用法
import "github.com/tangoui/tango/ui"
func page(c *ui.Context) {
ui.Affix(c).OffsetTop(0).Body(func() {
ui.Button(c, "保存").Primary()
})
}默认以窗口为视口,内容滚过顶部偏移量后固定。
常见用法
在滚动容器中固定
内容在 ScrollBox 内滚动时,把 scroll.ID() 传给 Target。目标 ID 在当前帧创建容器后才能取得,因此示例用状态保存上一帧的 ID。
import (
"github.com/tangoui/tango/ui"
"github.com/tangoui/tango/ui/layout"
)
var affixTarget ui.ID
func page(c *ui.Context) {
scroll := ui.Scroll(c, func() {
ui.Affix(c).OffsetTop(0).Target(affixTarget).Body(func() {
ui.Button(c, "保存").Primary()
})
for i := 0; i < 20; i++ {
ui.Paragraph(c, "滚动内容")
}
}, layout.H(240))
affixTarget = scroll.ID()
}固定到底部
OffsetBottom 让内容在接近视口底部时固定,例如保存栏。
import "github.com/tangoui/tango/ui"
func page(c *ui.Context) {
ui.Affix(c).OffsetBottom(16).Body(func() {
ui.Button(c, "提交").Primary()
})
}读取固定状态
调用 Body 后用 Affixed() 读取当前是否固定。滚动后的固定位置在绘制时计算,状态会在下一帧反映到这里。
import "github.com/tangoui/tango/ui"
func page(c *ui.Context) {
affix := ui.Affix(c).OffsetTop(8).Body(func() { ui.Text(c, "工具条") })
if affix.Affixed() {
ui.Text(c, "已固定")
} else {
ui.Text(c, "未固定")
}
}主题与样式
Affix 只负责定位,工具条的背景、边框、阴影和圆角可在 Body 内设置。ConfigProvider.Defaults("Affix", ui.Props{"offsetTop": 8}) 可设置默认顶部偏移,也支持数值键 offsetBottom。
注意事项
- 页面不是窗口滚动而是容器滚动时,必须设置
Target,否则偏移计算会以窗口为准。 - 目标容器 ID 需要稳定保存;不要在每帧用新值覆盖不同容器,否则固定状态会跳动。
- 固定内容不要遮住焦点元素;如顶部还有标题栏,给
OffsetTop留出空间。 - 固定工具条里的图标按钮仍需要
A11yLabel,键盘顺序不因固定而改变。 - RTL 只改变内容的方向,不改变上下偏移语义。
示例代码
以下是上方在线演示运行的 Go 源码(来自官方 gallery),点击标题展开。函数接收的 c *ui.Context 由窗口的 UI 循环每帧传入,接入方式见 Go GUI 入门。
API
签名与说明由 site/tools/compdoc 从 Go 源码和文档注释提取;点击名称跳到 Go API 参考 的对应条目。
入口函数
ui.Affix
func Affix(c *Context) *AffixWAffix starts a pinned block (default: offset top 0 in the window). Give it Target(scrollBox.ID()) when the page scrolls inside a container.
ConfigProvider.Defaults("Affix", ...) keys: "offsetTop", "offsetBottom" (numbers). Element's position="bottom" + offset is OffsetBottom.
返回 *AffixW,可链式调用的方法见 AffixW 方法。
AffixW 方法
ui.AffixW:AffixW pins its content to the viewport (or to a scroll container) once it would scroll past OffsetTop / OffsetBottom.
| 方法 | 说明 | 签名 |
|---|---|---|
Affixed | Affixed reports whether the content is currently pinned. | Affixed() bool |
Body | Body builds the pinned content. | Body(fn func()) *AffixW |
Changed | Changed reports a pin state change on the first build after it was detected. | Changed() bool |
OffsetBottom | OffsetBottom pins the content this far above the bottom of the viewport. | OffsetBottom(px float32) *AffixW |
OffsetTop | OffsetTop pins the content this far below the top of the viewport. | OffsetTop(px float32) *AffixW |
Target | Target uses a scroll container (ScrollBox.ID()) as viewport. | Target(id ID) *AffixW |