效果如图:本人亲测,直接贴代码:
步骤一:
html部分代码:
<template>
<div class="scrollLayout">
<!-- 内容 -->
<div class="content" ref="content">
<div v-for="i in 30" :key="i" style="width: 10rem; text-align: center">
{{ i }}
</div>
</div>
<!-- 滚动条 -->
<div class="scrollBar" ref="scrollBar">
<div class="slider" :style="`height:${sliderHeight}%;margin-top:${position}px;`"></div>
</div>
</div>
</template>
script部分代码:
<script setup>
import { ref, onMounted } from 'vue'
const content = ref(null); // ref绑定的内容元素
const scrollBar = ref(null); // ref绑定的手写滚动条
const sliderHeight = ref(0); // 滑块高度
const position = ref(0); // 手写滚动条的位置
// 初始化手写滚动条
onMounted(() => {
// clientHeight:容器的高度; scrollHeight:内容的高度
const { clientHeight: contentCH, scrollHeight: contentSH } = content.value;
const { clientHeight: scrollBarCH, scrollHeight: scrollBarSH } = scrollBar.value;
sliderHeight.value = (contentCH / contentSH) * 100; // 滑块高度(百分比)
let activeScrollDistance = scrollBarCH - scrollBarCH * (sliderHeight.value / 100); // 滑块可滑动距离
let contentScrollDistance = contentSH - contentCH; // 内容可滑动距离
console.log('容器的高度:', contentCH, '内容高度:', contentSH);
// 监听滚动
content.value.addEventListener('scroll', () => {
const { scrollTop } = content.value // scrollTop:内容滚动的距离
position.value = scrollTop * activeScrollDistance / contentScrollDistance; // 滑块需要滑动的距离
console.log('内容滚动距离: '+scrollTop+'px', '手写滑块需要移动的距离: ' + position.value +'px');
})
})
</script>
样式部分:
<style scoped>
.scrollLayout {
display: flex;
align-items: center;
padding: 1rem;
font-size: 1rem;
}
.content {
height: 20rem;
overflow: auto;
background: skyblue;
}
.scrollBar {
width: 5px; /* 滚动条的宽度 */
height: 18rem; /* 滚动条的高度 */
background-color: pink; /* 滚动条的颜色 */
margin-left: 1rem
}
.slider {
width: 100%;
background-color: palevioletred; /* 滑块的颜色 */
border-radius: 0.5rem; /* 滑块圆角 */
}
</style>
引入直接修改一下用就行了!!!