實現手淘金剛區類目列表的scroll滑動效果,我也不知道這種css效果的專業術語是什麼,就先這麼叫吧。。。css
(1)介紹html
(2)安裝vue
$ npm install @better-scroll/core@next --save
複製代碼
(1)實現效果其實很簡單,利用better-scroll
暴露出的兩個特性、translateX
、Math
對象git
(2)用better-scroll提供的方法計算出目前列表滾動位置佔整個寬度的百分比比,而後賦予translateX,就能夠實現二者實時的同步滾動了。代碼:github
<template>
<div class="home-category">
<div class="scroll-wrapper" ref="scroll">
<div class="scroll-content" ref="test">
<div class="scroll-item" v-for="(item, index) in cateList" :key="index">
<p class="text">{{item}}</p>
</div>
</div>
</div>
<div class="dot-wrapper">
<div class="dot" :style="{'transform': `translateX(${rate})`}"></div>
</div>
</div>
</template>
<script>
import BScroll from '@better-scroll/core';
export default {
data() {
return {
rate: 0,
cateList: [1, 2, 3, 4, 5, 6, 7],
};
},
mounted() {
this.init();
},
beforeDestroy() {
this.bs.destroy();
},
methods: {
init() {
this.bs = new BScroll(this.$refs.scroll, {
scrollX: true,
click: true,
probeType: 3, // listening scroll hook
});
const totalX = Math.abs(this.bs.maxScrollX);
this._registerHooks(['scroll'], (pos) => {
const currentX = Math.abs(pos.x);
this.rate = `${Number((currentX / totalX) * 100).toFixed(2)}%`;
});
},
_registerHooks(hookNames, handler) {
hookNames.forEach((name) => {
this.bs.on(name, handler);
});
},
},
};
</script>
<style lang="scss" scoped>
.home-category {
.scroll-wrapper {
width: 100%;
white-space: nowrap;
overflow: hidden;
}
.scroll-content {
display: inline-block;
.scroll-item {
// box-sizing: content-box;
height: 50px;
font-size: 24px;
display: inline-block;
text-align: center;
background: red;
padding: 0 32px;
line-height: 50px;
margin: 0 10px;
.text {
width: 88px;
}
}
}
.dot-wrapper {
width: 80px;
height: 4px;
background: rgba(0, 0, 0, 0.1);
border-radius: 3px;
margin: 0 auto;
margin-top: 20px;
overflow: hidden;
.dot {
box-sizing: border-box;
width: 40px;
height: 4px;
background: #f96c1d;
transition: all 0.4s linear;
}
}
}
</style>
複製代碼
最後看看咱們的實現效果(大體框架就是如此,效果自由發揮吧):
npm
咱們panda-mall首頁中也使用了這個常見的佈局方式-->首頁分類icon滑動api