Affix 固釘
捲動吸頂 / 吸底。用 IntersectionObserver 偵測佔位越界(無 scroll 節流開銷,無 IO 環境自動回退 scroll 監聽)。
基礎用法
吸頂 / 吸底(向下捲動頁面查看)
向下捲動頁面,工具條觸及虛線框頂部時吸頂,離開時復原。
吸頂狀態:未固定
向下捲動頁面,工具條觸及虛線框頂部時吸頂,離開時復原。
吸底狀態:未固定
import { useState } from 'react'
import { LhAffix, useLhLocale } from '@lh-ui/react'
export default function Demo() {
const { t } = useLhLocale()
const [topFixed, setTopFixed] = useState(false)
const [bottomFixed, setBottomFixed] = useState(false)
return (
<div className="demo-col">
<div className="demo-affix-zone">
<LhAffix offsetTop={8} onChange={setTopFixed}>
<div className="demo-affix-bar">{t('docs.affix.topBar')}</div>
</LhAffix>
<p className="demo-affix-text">{t('docs.affix.zoneHint')}</p>
</div>
<p>
{t('docs.affix.topState')}
{topFixed ? t('docs.affix.fixed') : t('docs.affix.unfixed')}
</p>
<div className="demo-affix-zone">
<LhAffix offsetBottom={8} onChange={setBottomFixed}>
<div className="demo-affix-bar">{t('docs.affix.bottomBar')}</div>
</LhAffix>
<p className="demo-affix-text">{t('docs.affix.zoneHint')}</p>
</div>
<p>
{t('docs.affix.bottomState')}
{bottomFixed ? t('docs.affix.fixed') : t('docs.affix.unfixed')}
</p>
</div>
)
}
offsetBottom 觸發吸底(優先於 offsetTop);target 指定捲動監聽容器(預設視口)。
Affix Props
| 屬性 | 說明 | 類型 | 可選值 | 預設值 |
|---|---|---|---|---|
| offsetTop | 距視口頂部多少像素觸發吸頂 | number | — | 0 |
| offsetBottom | 距視口底部多少像素觸發吸底(優先於 offsetTop) | number | — | 0 |
| target | 捲動監聽容器(選擇器或元素,預設視口) | string | HTMLElement | — | — |
| children | 固釘內容(對應 plus 的預設插槽) | ReactNode | — | — |
| sx | 快速佈局屬性 | SxProps | — | — |
Affix 事件
| 事件 | 說明 | 回呼簽名 | Vue 對照 |
|---|---|---|---|
| onChange | 固定態切換時觸發(進入或離開吸頂 / 吸底) | (fixed: boolean) => void | @change |
與 Vue 版的對應
offsetTop / offsetBottom / target / sx 與 lh-ui-plus 的 LhAffix 同名同義;
React 無插槽,plus 的預設插槽合併為 children,@change 對應 onChange。
防佈局跳動
固定態以佔位元素撐高(佔位保持文件流高度),固定元素等寬於佔位,內容不隨捲動抖動。
無障礙
無特殊 role;固定態不影響文件流焦點順序,固定元素層級走 --lh-affix-z-index(預設 900)。
樣式
import '@lh-ui/react/style/affix'