vue3 自定义滚动条,本人亲测,直接贴代码

效果如图:本人亲测,直接贴代码:

步骤一:  

    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>

引入直接修改一下用就行了!!!

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值