better-scroll的用法,及其中的一個屬性event._constructed詳解

better-scroll是一個頁面滾動插件,用它能夠很方便的實現下拉刷新,錨點滾動等功能。javascript

實現原理:父容器固定高度,並設置overflow:hidden,子元素超出父元素高度後將被隱藏,超出部分可滾動且沒有滾動條。vue

當即使用:

<body>
  <div id="wrapper">
    <ul>
       <li>...</li>
       <li>...</li>
       ...
    </ul>
  </div>
<script type="text/javascript" src="better-scroll.js"></script>
<script type="text/javascript">
  new BScroll(document.getElementById('wrapper'));
</script>
</body>

 

結合vue使用:

經過npm引入

1. 安裝better-scroll

npm install better-scrolljava

2. 頁面中引入better-scroll

import BScroll from 'better-scroll'git

3. 若是不支持import,可以使用

var BScroll require('better-scroll')github

頁面結構:npm

<div id="wrapper" ref="wrapper">
    <ul class="container">
       <li>...</li>
       <li>...</li>
       ...
    </ul>
</div>

 在methods中寫一個方法:app

 _initScroll() {
    this.boxScroll= new BScroll(this.$refs.wrapper, {
       click: true
    })
},

 注意:dom

  better-scroll會將點擊事件去掉,若是滾動部分須要有點擊事件,須要在參數里加上click:true。異步

  同時,在PC上或某些手機端,因爲未成功將touchend事件move掉,點擊事件會執行兩次。函數

  better-scroll派發的event事件和原生js的event有屬性上的區別,其中有一個屬性爲event._constructed。better-scroll派發的事件中event._constructed爲true,原生點擊事件中沒有這個屬性。

selectList(index,event){
    if(!event._constructed){//若是不存在這個屬性,則爲原生點擊事件,不執行下面的函數
        return
    }
}

 

因爲vue中數據更新是異步的,在dom解構沒有加載完成,BScroll沒法獲取目標容器的高度,會出現沒法滾動的現象。

vue中有一個方法能夠解決這個問題:$nextTick()

根據官方API的解釋可知,一些須要在頁面數據變化完成後才執行的函數須要寫在$nextTick中 。

this.$nextTick(() => {
    this._initScroll()
})

 

 

 附better-scroll參數:

  • startX: 0 開始的X軸位置
  • startY: 0 開始的Y軸位置
  • scrollX: true 滾動方向爲X軸
  • scrollY: true 滾動方向爲Y軸
  • click: true 是否啓用click事件
  • directionLockThreshold: 5
  • momentum: true 是否開啓動量動畫,關閉能夠提高效率
  • bounce: true 是否啓用彈力動畫效果,關掉能夠加速
  • selectedIndex: 0
  • rotate: 25
  • wheel: false 是否監聽鼠標滾輪事件
  • snap: false 自動分割容器,用於製做走馬燈效果等
  • snapLoop: false
  • snapThreshold: 0.1
  • swipeTime: 2500
  • bounceTime: 700 彈力動畫持續的毫秒數
  • adjustTime: 400
  • swipeBounceTime: 1200
  • deceleration: 0.001 滾動動量減速越大越快,建議不大於0.01
  • momentumLimitTime: 300
  • momentumLimitDistance: 15
  • resizePolling: 60 從新調整窗口大小時,從新計算better-scroll的時間間隔
  • preventDefault: true 是否阻止默認事件
  • preventDefaultException: { tagName: - /^(INPUT|TEXTAREA|BUTTON|SELECT)$/ } 阻止默認事件
  • HWCompositing: true 是否啓用硬件加速
  • useTransition: true 是否使用CSS3的Transition屬性,不然使用requestAnimationFram代替
  • useTransform: true 是否使用CSS3的Transform屬性
  • probeType: 1. 滾動的時候會派發scroll事件,會截流。2. 滾動的時候實時派發 - scroll事件,不會截流。 3. 除了實時派發scroll事件,在swipe的狀況下仍然能實時派發scroll事件

 

參考網站:

https://www.npmjs.com/package/better-scroll     better-scroll文檔

https://github.com/ustbhuangyi/better-scroll     github

相關文章
相關標籤/搜索