效果图:
代码:
<div class="gas-mode-item-body"><el-scrollbar style="width: 300px;height: 100%;" wrap-style="overflow-y:hidden" ref="scrollbarRef"><div style="display: flex"><el-tag class="list-item" v-for="(item,index) in items" @click="changeTargetIndex(index)" :class="targetIndex==index?'active-style':''" :key="index" style="margin:0 5px 5px 0">{{ item.text }}</el-tag></div></el-scrollbar></div><div @click="jumpNum">点击跳过去</div>
items: [{ text: 'Item 1' },{ text: 'Item 2' },{ text: 'Item 3' },{ text: 'Item 4' },{ text: 'Item 5' },{ text: 'Item 6' },{ text: 'Item 7' },{ text: 'Item 8' },{ text: 'Item 9' },// 更多项目...],targetIndex: 1, // 目标元素的索引
mounted() {this.scrollToItem(this.targetIndex);},
methods: {jumpNum(){this.targetIndex=8this.scrollToItem( this.targetIndex);},changeTargetIndex(index){this.targetIndex=indexthis.scrollToItem( this.targetIndex)},scrollToItem(index) {const itemElement = this.$refs.scrollbarRef.$el.querySelector(`.list-item:nth-child(${index + 1})`)console.log('1111',itemElement)if (itemElement) {const scrollContainer = this.$refs.scrollbarRef.$el.querySelector('.el-scrollbar__wrap');const targetScrollLeft = itemElement.offsetLeft;const currentScrollLeft = scrollContainer.scrollLeft;const duration = 500; // 动画持续时间,单位毫秒const startTime = performance.now();const animateScroll = (timestamp) => {const progress = timestamp - startTime;const easeInOutQuad = t => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;const percentage = Math.min(progress / duration, 1);const easedPercentage = easeInOutQuad(percentage);const newScrollLeft = currentScrollLeft + (targetScrollLeft - currentScrollLeft) * easedPercentage;scrollContainer.scrollLeft = newScrollLeft;if (progress < duration) {requestAnimationFrame(animateScroll);}};requestAnimationFrame(animateScroll);}},
}
css:
.gas-mode-item-body{/deep/ .el-scrollbar {.el-scrollbar__wrap {max-height: 200px; // 最大高度overflow-x: hidden; // 隐藏横向滚动栏margin-bottom: 6px !important;}}}
.list-item {min-width: 100px;padding: 10px;border: 1px solid #ccc;margin-right: 10px;
}
.active-style{background: #d43f3a;
}