Files
timi-web/docs/demos/utils/scroller.vue
T
2026-09-21 15:32:12 +08:00

118 lines
2.5 KiB
Vue

<template>
<div class="demo">
<div ref="boxRef" class="box">
<p class="tip" v-text="'滚动这个容器试试'" />
<div class="filler" />
<p ref="markRef" class="mark" v-text="'标记位置'" />
<div class="filler" />
</div>
<p class="state" v-text="`top=${state.top} bottom=${state.bottom} scrollHeight=${state.scrollHeight}`" />
<div class="bar">
<button type="button" class="btn" @click="scrollToMark" v-text="'toElement(标记)'" />
</div>
</div>
</template>
<script lang="ts" setup>
import { onMounted, onUnmounted, reactive, ref } from "vue";
import { Scroller } from "timi-web";
import type { ScrollListener } from "timi-web";
const LISTENER_NAME = "TimiDocsScrollerDemo";
const boxRef = ref<HTMLElement>();
const markRef = ref<HTMLElement>();
const state = reactive({
top: 0,
bottom: 0,
scrollHeight: 0
});
/** 传 getElement 时监听的是该容器的滚动,不传则监听 window。 */
function getElement() {
return boxRef.value;
}
function onScroll(event: ScrollListener) {
state.top = event.top;
state.bottom = event.bottom;
state.scrollHeight = event.scrollHeight;
}
/** toElement 会让目标滚动到可视区,这里目标在容器内,因此滚动的是容器。 */
function scrollToMark() {
if (markRef.value) {
Scroller.toElement(markRef.value);
}
}
onMounted(() => {
Scroller.addListener(LISTENER_NAME, onScroll, getElement);
// 首次同步一次状态
onScroll({ top: 0, bottom: 0, scrollHeight: boxRef.value?.scrollHeight ?? 0 } as ScrollListener);
});
onUnmounted(() => {
Scroller.removeListener(LISTENER_NAME);
});
</script>
<style lang="less" scoped>
.demo {
.box {
height: 12rem;
padding: 0 1rem;
margin-bottom: .75rem;
overflow-y: auto;
border: 1px solid var(--vp-c-divider);
border-radius: .5rem;
background: var(--vp-c-bg-soft);
}
.tip {
margin: 1rem 0;
font-size: .8125rem;
color: var(--vp-c-text-2);
}
.mark {
margin: 0;
padding: .5rem;
font-size: .8125rem;
text-align: center;
border-radius: .375rem;
color: var(--vp-c-brand-1);
background: var(--vp-c-default-soft);
}
.filler {
height: 14rem;
}
.state {
margin: 0 0 .75rem;
font-size: .75rem;
font-family: monospace;
color: var(--vp-c-text-2);
}
.btn {
padding: .25rem .75rem;
font-size: .75rem;
cursor: pointer;
border: 1px solid var(--vp-c-divider);
border-radius: .375rem;
color: var(--vp-c-text-1);
background: var(--vp-c-bg-soft);
&:hover {
color: var(--vp-c-brand-1);
border-color: var(--vp-c-brand-1);
}
}
}
</style>