描述
模擬vant的Tab標(biāo)簽頁(yè)的標(biāo)簽滾動(dòng)效果
效果:選中元素播揪,在滾動(dòng)條的可視區(qū)域里面自動(dòng)居中瞒爬,頭尾兩端不用居中
vant效果:https://youzan.github.io/vant/#/zh-CN/tab
vant效果.jpg
代碼
<template>
<div>
<div class="scroll-box" ref="scrollBox">
<div
ref="scrollItem"
class="item"
:class="{ active: currentIndex == index }"
v-for="(item, index) in 10"
:key="index"
>
{{ index }}
</div>
</div>
<div class="tips">點(diǎn)擊加減號(hào)改變索引再點(diǎn)擊啟動(dòng)按鈕排作,觀察滾動(dòng)!=俊创橄!</div>
<div>當(dāng)前索引是:{{ currentIndex }}</div>
<div class="input-box">
<div class="action">
<div class="item" @click="reduce">-</div>
<div class="item num">{{ currentIndex }}</div>
<div class="item" @click="add">+</div>
</div>
<div class="start" @click="start">啟動(dòng)</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentIndex: 0
}
},
methods: {
add() {
this.currentIndex++
},
reduce() {
this.currentIndex--
},
start() {
/**
* 1)先讓選中的元素滾到可視區(qū)域的最左邊 scrollLeft
* 2)接著向右移動(dòng)容器一半的距離 containWidth / 2
* 3)最后向左移動(dòng)item一半的距離 offsetWidth / 2
*/
let lastSpot = this.$refs.scrollBox.scrollLeft
const nextSpace = 7 //每次移動(dòng)距離
let scrollItemTimer = setInterval(() => {
this.$nextTick(() => {
let offsetWidth = this.$refs.scrollItem[this.currentIndex].offsetWidth //item
let scrollLeft = this.$refs.scrollItem[this.currentIndex].offsetLeft //選中的元素滾到可視區(qū)域的最左邊
const containWidth = this.$refs.scrollBox.offsetWidth //容器的寬度
let resultSpot = scrollLeft + offsetWidth / 2 - containWidth / 2 //最終要停留的點(diǎn)
if (Math.abs(lastSpot - resultSpot) < nextSpace) {
clearInterval(scrollItemTimer)
}
if (resultSpot >= lastSpot) {
lastSpot = lastSpot + nextSpace
} else {
lastSpot = lastSpot - nextSpace
}
this.$refs.scrollBox.scrollTo(lastSpot, 0)
})
}, 15)
}
}
}
</script>
<style lang="less" scoped>
.scroll-box {
margin-top: 50px;
width: 330px;
height: 40px;
background-color: #ddd;
white-space: nowrap;
overflow-y: hidden;
overflow-x: scroll;
.item {
display: inline-block;
height: 100%;
width: 90px;
border-radius: 5px;
background-color: #ff0;
margin-right: 10px;
text-align: center;
line-height: 40px;
}
.item:nth-last-of-type(1) {
margin-right: 0;
}
}
.active {
background-color: #0ff !important;
}
.tips {
margin-top: 30px;
font-weight: 700;
color: #1989fa;
}
.input-box {
width: 100%;
display: flex;
align-items: center;
.action {
display: flex;
align-items: center;
.item {
width: 40px;
height: 40px;
background-color: #07c160;
color: #fff;
text-align: center;
line-height: 40px;
border-radius: 10px;
margin-right: 5px;
}
.item.num {
background-color: #ff976a;
}
}
.start {
width: 80px;
height: 40px;
background-color: #1989fa;
color: #fff;
margin-left: 100px;
text-align: center;
line-height: 40px;
border-radius: 10px;
}
}
</style>
圖片效果
居中滾動(dòng).gif
動(dòng)動(dòng)手指點(diǎn)贊
如果這篇文章對(duì)你有用,請(qǐng)給我點(diǎn)個(gè)贊,讓我更加有動(dòng)力寫(xiě)下去,謝謝