使用步骤
给需要使用的元素绑定ref
<main
ref="mainElement"
v-back-to-top="enableBackToTop"
class="relative flex-1 overflow-x-hidden"
:style="{ overflowY: scrollable ? 'scroll' : 'hidden' }"
@scroll="handleScroll"
>
<div
class="fixed left-0 z-50 adapt-top-44 bottom-0"
style="width: 15pt"
@touchmove.prevent
></div>
<slot></slot>
</main>
获取元素
const mainElement = ref();
创建一个navigator的透明度属性
const navigatorOpacity = ref(1);
navigator的透明度随着滚动容器的 scrollTop 出现
navigatorOpacity.value = Math.min(1,mainElement.value.scrollTop / 64);
给滚动元素绑定style属性,值为
:style={background:`rgba(217,241,255,${navigatorOpacity})`}
例子(本项目通过组件传参的方式使用)
子组件
<template>
<main
ref="mainElement"
v-back-to-top="enableBackToTop"
class="relative flex-1 overflow-x-hidden"
:style="{ overflowY: scrollable ? 'scroll' : 'hidden' }"
@scroll="handleScroll"
>
<div
class="fixed left-0 z-50 adapt-top-44 bottom-0"
style="width: 15pt"
@touchmove.prevent
></div>
<slot></slot>
</main>
</template>
<script setup lang="ts">
import { ref } form 'vue';
interface Emits {
(e: 'back'): void;
(e: 'scroll', top: number): void;
}
const emit = defineEmits<Emits>();
const mainElement = ref();
const navigatorOpacity = ref(1);
const handleScroll = () => {
navigatorOpacity.value = Math.min(1, mainElement.value.scrollTop / 64);
emit('scroll', mainElement.value.scrollTop);
};
</script>
父组件
滚动容器上添加这两条属性
<template>
<div :navBackgroundColor="`rgba(217,241,255,${navigatorOpacity})`"
@scroll="navigatorOpacity = Math.min(1, $event / 64)"
>
<!-- 内容 -->
</div>
</template>
<script setup lang="ts">
const navigatorOpacity = ref(0);
</script>