效果图
实现思路
- 固定整个灰色滚动条的长度
- 计算可滚动区域占整个可视视图的比例,来确定橙色块的长度
- 监听页面滚动,计算橙色块向右偏移距离
主要代码
template:
<div v-show="showBar" ref="barRef" class="scrollbar" :style="{ bottom }"><div ref="thumbRef" class="thumb" />
</div>
script:
import { defineProps, ref } from 'vue'const props = defineProps({bottom: {type: String,default: '0',},
})
const showBar = ref(true)
const thumbRef = ref(null)
const barRef = ref(null)
function init(containerRef, contentRef) {console.log(containerRef)const boxWidth = containerRef.offsetWidthconst contentWidth = contentRef.scrollWidthconst thumbWidth = (boxWidth / contentWidth) * barRef.value.offsetWidththumbRef.value.style.width = `${thumbWidth}px`if (thumbWidth >= 60) {showBar.value = false}
}
function scrollHandler(containerRef, contentRef) {const boxWidth = containerRef.offsetWidthconst contentWidth = contentRef.scrollWidthconst scrollRatio = contentRef.scrollLeft / (contentRef.scrollWidth - containerRef.offsetWidth)const thumbWidth = (boxWidth / contentWidth) * barRef.value.offsetWidththumbRef.value.style.left = `${scrollRatio * (barRef.value.offsetWidth - thumbWidth)}px`
}defineExpose({init,scrollHandler,
})
css:
.scrollbar {position: absolute;left: 50%;transform: translateX(-50%);width: 60px;height: 4px;border-radius: 100px;background: #E8E8EA;.thumb {position: absolute;left: 0;top: 0;height: 100%;background: linear-gradient(270deg, #E24128 0%, #E65834 100%);border-radius: 100px;}
}