Skip to content

useScrollToElement

将滚动容器内指定索引(或最后一项)的子元素滚动到可视区域。

基础用法

列表项 1
列表项 2
列表项 3
列表项 4
列表项 5
列表项 6
列表项 7
列表项 8
列表项 9
列表项 10
列表项 11
列表项 12
列表项 13
列表项 14
列表项 15
列表项 16
列表项 17
列表项 18
列表项 19
列表项 20
列表项 21
列表项 22
列表项 23
列表项 24
列表项 25
列表项 26
列表项 27
列表项 28
列表项 29
列表项 30
查看代码
vue
<template>
    <div>
        <div
            ref="scrollContainerRef"
            style="height: 140px; overflow: auto; padding: 12px; background: #fafafa; border-radius: 8px"
        >
            <div v-for="n in 30" :key="n" style="padding: 6px">列表项 {{ n }}</div>
        </div>
        <div style="margin-top: 12px">
            <Button @click="scroll(19, { behavior: 'smooth' })">滚动到第 20 项</Button>
            <Button @click="scroll('latest')">滚动到最后一项</Button>
        </div>
    </div>
</template>

<script setup lang="ts">
import { Button, useScrollToElement } from "@a-drowned-fish/rox-v";

const { scrollContainerRef, scroll } = useScrollToElement();
</script>

签名

ts
function useScrollToElement(queryCondition?: string): {
    scrollContainerRef: Ref<HTMLElement | null>;
    scroll: (pos: number | "latest", options?: boolean | ScrollIntoViewOptions, dir?: "ltr" | "rtl" | "auto") => void;
};

参数

参数说明
queryCondition选择器,指定滚动容器;不传则使用 scrollContainerRef

scroll 方法

参数说明
pos子元素索引(number)或 "latest"(最后一项)
options透传给 scrollIntoView 的选项(booleanScrollIntoViewOptions
dir书写方向;"rtl" 时对第一项 / 最后一项做镜像处理

返回值

字段说明
scrollContainerRef滚动容器模板 ref
scroll执行滚动的方法

基于 MIT 协议开源