BackTop 返回顶部
滚动超过阈值出现、点击回顶。平滑滚动走原生 scrollTo({ behavior: 'smooth' }),prefers-reduced-motion 自动降级。
基础用法
基础用法(向下滚动查看)
vue
<script setup lang="ts">
</script>
<template>
<!-- 基础用法 -->
<LhBackTop :right="24" :bottom="24" />
</template>vue
<script>
export default {}
</script>
<template>
<!-- 基础用法 -->
<LhBackTop :right="24" :bottom="24" />
</template>visibility-height 自定义出现阈值,smooth 关闭平滑滚动,target 监听指定滚动容器。
自定义阈值与关闭平滑
vue
<script setup lang="ts">
</script>
<template>
<!-- 自定义阈值与关闭平滑 -->
<LhBackTop :visibility-height="80" :smooth="false" :right="24" :bottom="90" />
</template>vue
<script>
export default {}
</script>
<template>
<!-- 自定义阈值与关闭平滑 -->
<LhBackTop :visibility-height="80" :smooth="false" :right="24" :bottom="90" />
</template>滚动停止(scrollend)
@scrollend 在滚动停止时抛出当前滚动距离:原生 scrollend 事件优先 (Chromium 114+ / Safari 18.2+),旧浏览器自动退回 scroll + 150ms 防抖。常用于锚点联动、数据懒加载。
scrollend 事件
最近一次停止位置:(未滚动)
vue
<script setup>
import { ref } from 'vue'
const lastStop = ref('(未滚动)')
function onScrollEnd(scrollTop) {
lastStop.value = `${scrollTop}px`
}
</script>
<template>
<LhBackTop :right="24" :bottom="160" @scrollend="onScrollEnd" />
</template>vue
<script>
export default {
data() {
return { lastStop: '(未滚动)' }
},
methods: {
onScrollEnd(scrollTop) {
this.lastStop = `${scrollTop}px`
},
},
}
</script>
<template>
<LhBackTop :right="24" :bottom="160" @scrollend="onScrollEnd" />
</template>API
LhBackTop Props
| 属性名 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| target | 滚动容器(选择器或元素,默认视口) | string | HTMLElement | — |
| visibilityHeight | 滚动多少像素后出现 | number | 200 |
| right | 距右侧偏移 px | number | 40 |
| bottom | 距底部偏移 px | number | 40 |
| smooth | 是否平滑滚动 | boolean | true |
| sx | sx 快速布局属性 | LhSxProps | — |
Events
| 事件名 | 说明 | 回调参数 |
|---|---|---|
| click | 点击按钮时触发(随后执行回顶滚动) | (event: MouseEvent) |
| scrollend | 滚动停止时触发,携带当前滚动距离 | (scrollTop: number) |
插槽:default(自定义内容)。
无障碍
- 真实
<button>,纯图标形态必须命名(语言包backtop.label) - 出现/消失不进入焦点树冲突(隐藏时
v-if移出)
类型定义
本组件对外导出的 TypeScript 类型结构如下(自动提取自 packages/components/backtop/src/types.ts 与 @lh-ui/share/core/* 源码,点击各条目展开查看完整定义;属性说明见上方 Props 表):
LhBackTopProps
ts
export interface LhBackTopProps {
/** 滚动容器(选择器或元素,默认视口) */
target?: string | HTMLElement
/** 滚动多少像素后出现 */
visibilityHeight?: number
/** 距右侧偏移 px */
right?: number
/** 距底部偏移 px */
bottom?: number
/** 是否平滑滚动 */
smooth?: boolean
/** sx 快速布局属性 */
sx?: LhSxProps
}常量
本组件用到的公开常量如下(可在 Props 表的「类型 / 默认值」列点击同名条目跳转至此):
LH_BACKTOP_VISIBILITY_HEIGHT_DEFAULT (来自 @lh-ui/share/core/backtop)
ts
/** 默认滚动阈值 px */
export const LH_BACKTOP_VISIBILITY_HEIGHT_DEFAULT = 200LH_BACKTOP_SCROLLEND_DELAY (来自 @lh-ui/share/core/backtop)
ts
/** scrollend 防抖兜底的静止阈值 ms(仅在不支持原生 scrollend 的浏览器使用) */
export const LH_BACKTOP_SCROLLEND_DELAY = 150