vue3 封装自定义滚动条组件

<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 })

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值