<template>
<!-- 内容部分加class="content" ref="content" 再inject -->
<div ref="scrollBar" class="scrollBars" :style="``">
<div style="position: relative;height: 100%;">
<div class="slider" :style="`width:200% ;height:${sliderHeight}%;margin-top:${position}px;background:${sliderColor};border-radius: 3px;`"></div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted, inject } from 'vue';
const content = inject('content'); // 父级内容元素
const { scrollWidth, scrollHeight, scrollColor, sliderColor, scrollId } = defineProps({
scrollWidth: {
type: String,
default: '0.13',
},
scrollHeight: {
type: String,
default: '4',
},
scrollColor: {
type: String,
default: '#293047',
},
sliderColor: {
type: String,
default: 'linear-gradient(#697083, #f1f3f4)',
},
scrollId: {
type: String,
required: true,
},
});
const scrollBar = ref(null); // 滚动条元素
const sliderHeight = ref(0); // 滑块高度
const position = ref(0); // 滚动条的位置
// 初始化手写滚动条
onMounted(() => {
// console.log(content ,'contentcontent');
// clientHeight:容器的高度; scrollHeight:内容的高度
const { clientHeight: contentCH, scrollHeight: contentSH } = content[scrollId].value;
const { clientHeight: scrollBarCH } = scrollBar.value;
sliderHeight.value = (contentCH / contentSH) * 100; // 滑块高度(百分比)
let activeScrollDistance = scrollBarCH - scrollBarCH * (sliderHeight.value / 100); // 滑块可滑动距离
let contentScrollDistance = contentSH - contentCH; // 内容可滑动距离
// console.log('容器的高度:', contentCH, '内容高度:', contentSH);
// 监听滚动
content[scrollId].value.addEventListener('scroll', () => {
const { scrollTop } = content[scrollId].value; // scrollTop:内容滚动的距离
position.value = (scrollTop * activeScrollDistance) / contentScrollDistance; // 滑块需要滑动的距离
// console.log('内容滚动距离: '+scrollTop+'px', '手写滑块需要移动的距离: ' + position.value +'px');
});
});
</script>
<style>
.scrollBars {
width: 5px;
height: 100%;
background: #3a405b;
position: absolute;
right: 11px;
top: 0;
border-radius: 3px;
}
.slider{
position: absolute;
left: -2px;
}
</style>
scroll.vue
页面中
import scroll from '../../components/scroll.vue';
组件上加 <scroll scrollId="content1" />
内容盒子加上 ref="content1"
const content1 = ref(null) //ref
provide('content', { content1 })