国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

vue中實現左右聯動的效果

2019-11-19 13:37:13
字體:
來源:轉載
供稿:網友

這里的坑還是蠻多的,花了一個多小時,才理清楚。

 做一下筆記,以便于復習。

首先呢,需要讓左右的布局都可以滾動,這里使用了betterScroll

npm i better-scrollimport BScroll from 'better-scroll'methods: {  _initScroll () {   this.menuScroll = new BScroll((this.$refs.menu), {    click: true    因為betterscroll默認會阻止點擊事件。這里要設置一下   })   this.foodScroll = new BScroll((this.$refs.good), {    probeType: 3    用來獲取滾動的距離   })   this.foodScroll.on('scroll', (pos) => {    this.scrollY = Math.abs(Math.round(pos.y))   })  },

重點:

created () {  this.$ajax.get('/api/data.json').then((res) => {   this.goods = res.data.goods   this.$nextTick(() => {    this._initScroll()    this.getGoodsHeight()   })  }) },

這里的代碼一定要在獲取數據里面寫nextTick()回調里面寫代碼,因為需要等待數據萬泉加載再去初始化scroll和獲取右邊每一個盒子的高度。

說道高度,高度如何獲取呢?

getGoodsHeight () {   let goodEle = this.$refs.good   let height = 0   this.listHeight.push(height)   let foodList = goodEle.getElementsByClassName('goodsItemHook')   for (let i = 0; i < foodList.length; i++) {    let item = foodList[i]    height += item.clientHeight    this.listHeight.push(height)   }  },

這里是獲取到每一個盒子的clientHeight的高度進行疊加,在push到一個數組里面。

this.foodScroll.on('scroll', (pos) => {    this.scrollY = Math.abs(Math.round(pos.y))   })

獲取滾動的值,賦值給scrollY。

然后根據scrollY 和listHeight的高度區間做對比,拿到index:

currentIndex () {   for (let i = 0; i < this.listHeight.length; i++) {    let height1 = this.listHeight[i]    let height2 = this.listHeight[i + 1]    if (!height2 || (this.scrollY < height2 && this.scrollY >= height1)) {     return i    }   }  }

這時候滾動就能獲取index的值了,然后給左邊的元素去添加active的樣式就方便了。

:class="{'active': currentIndex == index}" 

最后一步是如何實現點擊的時候去讓右邊的滾動到指定的位置。

handleGoodsItem (index) {   let goodEle = this.$refs.good   let foodList = goodEle.getElementsByClassName('goodsItemHook')   let el = foodList[index]   this.foodScroll.scrollToElement(el, 300)  }

這里調用了scroll的方法:scrollToElement。

總結

以上所述是小編給大家介紹的vue中實現左右聯動的效果,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 自治县| 崇礼县| 神农架林区| 竹溪县| 偏关县| 周口市| 河东区| 松溪县| 康定县| 伽师县| 察隅县| 马公市| 庄浪县| 石屏县| 徐闻县| 洮南市| 德格县| 凌海市| 盐津县| 安西县| 班玛县| 玉环县| 舟曲县| 建水县| 丘北县| 南平市| 佛山市| 上饶市| 绥化市| 清水河县| 宁安市| 图们市| 涞水县| 康乐县| 拜泉县| 东平县| 普格县| 收藏| 钟祥市| 潢川县| 潢川县|