监听滚动盒子的 水平滚动距离占它自身的总宽度的比
来改变指示条的位置
示例图
javsScript
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
// 绑定要监听的滚动盒子的dom元素
const container = ref(null)
// 滚动盒子的总宽度
const cw = ref(1050)
// 监听到的水平滚动距离
const x = ref(0)
// 水平滚动距离占总宽度的百分比(滚动距离/总宽度)
const cLeft = ref(0)
// 滚动事件
const onScroll = () => {
// container.value可能会拿到null,不写判断会报错
if(container.value){
x.value = container.value.scrollLeft
cLeft.value = Math.floor((x.value / cw.value) * 100)
}
}
onMounted(() => {
// 开启监听
window.addEventListener('scroll', onScroll, true)
})
onBeforeUnmount(() => {
// 停止监听
window.removeEventListener('scroll', onScroll)
})
</script>
html
<template>
<!-- 利用给nav-wrapper标签设置overflow:hidden隐藏滚动条 -->
<div class="nav-wrapper">
<div class="play-nav" ref="container">
<!-- 本来我这里放的是图片,但是篇幅太长,这里直接用固定宽度代替 -->
<div style="width: 1050px"></div>
</div>
</div>
<div class="dot-wrapper" ref="dotWrapper">
<!-- 水平滚动距离占总宽度的百分比 -->
<div class="dot" :style="`left: ${cLeft}% ;`"></div>
</div>
</template>
scss
<style lang="scss" scoped>
.nav-wrapper{
width: 100vw;
// 当高度小于滚动盒子的高度时,可以将滚动条隐藏
height: 24vw;
overflow: hidden;
.play-nav{
width: 100vw;
height: 26vw;
overflow: auto;
display: flex;
}
}
.dot-wrapper{
width: 8vw;
height: 1.1vw;
border-radius: 1vw;
background-color: #eee;
margin: 0 auto;
position: relative;
.dot{
position: absolute;
left: 0%;
width: 3vw;
height: 1.1vw;
border-radius: 1vw;
background-color: #f44;
}
}
</style>