useScrollToEdge
将容器内匹配的元素「最小化」滚动到视口边缘(偏前则贴前边界,偏后则贴后边界)。与 useScrollToCenter 不同,它只滚动到刚好可见,而不是居中。
基础用法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
查看代码
vue
<template>
<div>
<div
ref="scrollContainerRef"
style="display: flex; gap: 8px; overflow-x: auto; padding: 12px; background: #fafafa; border-radius: 8px"
>
<div
v-for="n in 20"
:key="n"
:data-item="n"
style="
flex: 0 0 auto;
width: 80px;
height: 80px;
display: flex;
align-items: center;
justify-content: center;
background: #ff7a45;
color: #fff;
border-radius: 8px;
"
>
{{ n }}
</div>
</div>
<div style="margin-top: 12px">
<Button @click="scrollTo18">将第 18 项滚动到视口边缘</Button>
</div>
</div>
</template>
<script setup lang="ts">
import { Button, useScrollToEdge } from "@a-drowned-fish/rox-v";
const { scrollContainerRef, scroll } = useScrollToEdge();
const scrollTo18 = () => scroll("[data-item='18']");
</script>签名
ts
function useScrollToEdge(queryCondition?: string): {
scrollContainerRef: Ref<HTMLElement | null>;
scroll: (selectorCondition: string, options?: ScrollOptions) => void;
};
interface ScrollOptions {
behavior?: ScrollBehavior; // 默认 "smooth"
direction?: "vertical" | "horizontal"; // 默认 "horizontal"
dir?: "rtl" | "ltr" | "auto"; // 默认 "auto"
}返回值
| 字段 | 说明 |
|---|---|
scrollContainerRef | 滚动容器模板 ref |
scroll | (selectorCondition, options) 滚动到匹配元素边缘 |
与 useScrollToCenter 的区别
useScrollToCenter:把元素滚动到容器中心。useScrollToEdge:只把元素滚动到刚好进入视口(贴边),滚动位移更小。