View Transitions 与表单提交流程协同与可访问性回退概述表单提交流程需兼顾校验提示与页面过渡体验。通过 View Transitions 的封装与 BFCache 事件处理,可实现稳定的导航与返回恢复。关键参数/概念过渡封装:在提交成功跳转或局部状态更新时使用 `startViewTransition`。BFCache 兼容:`pageshow/pagehide` 事件处理提交后返回的焦点与状态。无障碍:减弱动画与键盘可达性保证提示信息可见。实践/示例<form id="signup" method="post" action="/submit">

<input name="email" required aria-describedby="email-desc" />

<div id="email-desc">请输入有效邮箱</div>

<button type="submit">提交</button>

</form>

<script>

const form = document.getElementById('signup')

form.addEventListener('submit', async (e) => {

e.preventDefault()

const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches

const run = async () => {

const res = await fetch(form.action, { method: 'POST', body: new FormData(form) })

if (res.ok) {

const html = await res.text()

document.open(); document.write(html); document.close()

} else {

const data = await res.json().catch(() => ({}))

// 显示错误提示并保持焦点可达

alert(data.message || '提交失败')

}

}

if (reduce || !document.startViewTransition) { run(); return }

document.startViewTransition(() => run())

})

// BFCache 返回后保持输入与焦点位置

window.addEventListener('pageshow', (e) => {

if (e.persisted) {

const active = document.activeElement

if (active && typeof active.scrollIntoView === 'function') {

active.scrollIntoView({ block: 'nearest' })

}

}

})

</script>

验证方法表单错误路径:确认提示信息在降级与过渡下均可见与可达。返回导航:提交后返回是否保留输入状态与焦点。指标:采集 INP 与导航耗时,对比封装与未封装方案。注意事项避免在过渡期间改变参与元素尺寸,减少闪烁。键盘与读屏路径优先,动画不可替代信息表达。使用 `pagehide` 而非 `unload` 做清理以兼容 BFCache。参考资料MDN: `pageshow`/`pagehide` 与 BFCache(2025 更新)https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_eventhttps://developer.mozilla.org/en-US/docs/Web/API/Window/pagehide_eventMDN: ViewTransition 与 `startViewTransition()`(2025-11 更新)https://developer.mozilla.org/en-US/docs/Web/API/Document/startViewTransitionhttps://developer.mozilla.org/en-US/docs/Web/API/ViewTransition

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部