滾動位置固定:在vue中通過路由切換頁面時組件會自動滾動到頂部,需要監聽滾動行爲才能讓滾動位置固定,better-scroll解決了這個問題。
常用效果:移動端很常見的效果,當滑動右邊部分的時候,左邊會聯動顯示與當前內容相符合的標題高亮,當點擊左邊某一個標題的時候,右邊會自動滑動到相應的內容。
npm install better-scroll --save
import BScroll from 'better-scroll'
注意使用better-scroll的基本條件
- 必須包含兩個大的div,外層和內層div
- 外層div設置可視的大小(寬或者高)-有限制寬或高
- 內層div,包裹整個可以滾動的部分
- 內層div高度一定大於外層div的寬或高,才能滾動
//創建一個新實例 並且 對class爲wrapper對象 實現了一個縱向可點擊的滾動效果
let scroll = new BScroll('.wrapper',{
scrollY: true,
click: true
})
實現及說明
1.滾動效果
better-scroll在使用的時候需要在dom元素渲染完成之後初始化better-scroll的實例,初始化的時候,先要獲取需要滑動的元素,然後在初始化的時候將獲取到的元素傳遞給初始化函數,此時便可實現滑動效果
2.左右聯動效果
左右聯動效果的實現,是better-scroll通過監聽事件實現的。
首先獲取到右邊內容盒子的高度,然後獲取到該盒子中每一項的高度並做前n項高度累加(第n項的高度是前n項的高度和)存儲到listHeight數組中。在初始化的時候傳遞屬性probeType=3 (探針的效果,時時獲取滾動高度),並給右邊的內容盒子對象監聽scroll事件,從而時時獲取Y軸位置,來與listHeight數組中的數據做比較,時時計算當前的索引值,並給對邊對應索引值的項添加背景色高亮,從而實現右邊滑動,聯動左邊。
當點擊左邊的每一項的時候,獲取到當前的索引值,並根據當前的索引值獲取到與右邊內容盒子中對應索引的元素,右邊的盒子元素通過監聽scrollToElement,並傳遞獲取到的對應索引元素和動畫時間,從而實現點擊左邊,實現右邊聯動;
probeType
- 類型:Number
- 默認值:0
- 可選值:1、2、3
- 作用:有時候我們需要知道滾動的位置。當 probeType 爲 1 的時候,會非實時(屏幕滑動超過一定時間後)派發scroll 事件;當 probeType 爲 2 的時候,會在屏幕滑動的過程中實時的派發 scroll 事件;當 probeType 爲 3 的時候,不僅在屏幕滑動的過程中,而且在 momentum 滾動動畫運行過程中實時派發 scroll 事件。
<template>
<div class="scroll" ref='wrapper'>
<slot></slot>
</div>
</template>
<script>
import BScroll from 'better-scroll'
export default {
name: 'scroll',
props:{
//縱向滾動
scrollY: {
type: Boolean,
default: true
},
//橫向滾動
scrollX:{
type: Boolean,
default: false
},
click:{
type: Boolean,
default: true
},
//探針
probeType: {
type: Number,
default: 0
}
},
//掛載後
mounted(){
let wrapper = this.$refs.wrapper
this.scroll = new BScroll(wrapper,{
scrollX:this.scrollX,
scrollY:this.scrollY,
click: this.click,
probeType: this.probeType
})
//console.log('scroll', this.scroll)
// //監聽滾動事件
this.scroll.on('scroll',position => {
//scroll組件不關心你要幹嘛,只需要把你想要的信心給你,也就是派發scroll事件,如果你想獲取實時的滾動位置你來監聽這個事件即可,position就是實時滾動的位置,是個對象,{x: 0 ,y: 0} y是個負值
this.$emit('scroll',position)
})
},
methods:{
// //滾動到指定元素
scrollToElement(...args) {
this.scroll && this.scroll.scrollToElement(...args)
},
//滾動到相應的位置
scrollTo(...args){
this.scroll&&this.scrollTo(...args)
},
//刷新
refresh(){
this.scroll&&this.scroll.refresh()
},
//禁用
disable(){
this.scroll&&this.scroll.disable()
},
//啓用
enble(){
this.scroll&&this.scroll.enable()
}
}
}
</script>
<style>
.scroll{
overflow:hidden;
}
</style>
在組件中如要用到scroll,就引入.
如: import scroll from '../../base/scroll/scroll'
再在定義:components:{
srcoll
}
<scroll>
<div class= 'bigBox'> 有固定的高度
<div class=" box"> box的高度一定要高於外邊的父級盒子,才能實現滾動
</div>
</div>
</scroll>
例如: