效果圖
實現思路
- 固定整個灰色滾動條的長度
- 計算可滾動區域占整個可視視圖的比例,來確定橙色塊的長度
- 監聽頁面滾動,計算橙色塊向右偏移距離
主要代碼
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;}
}