vue 横向滚动菜单点击居中
最近在写项目的时候遇到一个功能 vue 横向滚动菜单实现点击 元素滚动可视区域居中,网上找了一些轮子都不是很好用,决定自己写一个,话不多说,开撸
先上效果如下,点击后面item可自动滚动到可视区域

在template中的代码
<div class="navbar-list"> <div class="flex-imd" id="flexImd"> <div v-for="(item, index) in courseTypeList" :key="index" class="navbar-item" :class="currNavbar === index ? 'act' : 'nol'" @click="chooseNav(index)" > <img :src="item.typeLogo" alt="" class="navbar-item-img" style="pointer-events: none" /> {{ item.typeName }} </div> </div> </div>
script中的代码(url可自己找一些资源,这里我就不放了)
export default { data () { return { currNavbar: 0, courseTypeList: [{ typeName: '测试标题001', typeLogo: 'imgurl' }, { typeName: '测试标题001', typeLogo: 'imgurl' }, { typeName: '测试标题001', typeLogo: 'imgurl' }, { typeName: '测试标题001', typeLogo: 'imgurl' }, { typeName: '测试标题001', typeLogo: 'imgurl' }, { typeName: '测试标题001', typeLogo: 'imgurl' }, { typeName: '测试标题001', typeLogo: 'imgurl' }] } }, methods: { chooseNav (index) { this.currNavbar = index this.$nextTick(() => { const item = this.$el.querySelectorAll('.navbar-item')[index] const container = document.querySelector('#flexImd') const scrollLeft = item.offsetLeft - (container.offsetWidth - item.offsetWidth) / 2 container.scrollTo({ left: scrollLeft, behavior: 'smooth' }) }) } } }
css样式代码 (这里自己写了一部分css样式代码,可以改成自己项目中的样式即可)
.flex-imd {
display : flex;
overflow-x: scroll ;
padding : 0 ;
}
.flex-imd::-webkit-scrollbar {
display : none ;
}
.navbar-list {
width : 100% ;
padding : 10px ;
}
.navbar-item {
width : max-content;
white-space : nowrap ;
padding : 0px 18px ;
margin : 0px 5px ;
box-sizing: border-box;
height : 30px ;
display : flex;
border-radius: 15px ;
color : white ;
font-weight : 900 ;
font-size : 12px ;
flex-flow: column nowrap ;
justify- content : space-around;
align-items: center ;
cursor : pointer ;
display : flex;
flex- direction : row;
align-items: center ;
}
.navbar-item-img {
width : 20px ;
height : 20px ;
margin-right : 5px ;
}
.navbar-list::-webkit-scrollbar {
display : none ;
}
.navbar-item.act {
background : #c30f20 ;
}
.nol {
background : #999999 ;
}


浙公网安备 33010602011771号