您的位置:首頁技術文章
文章詳情頁

vue監聽滾動事件的方法

瀏覽:3日期:2022-10-17 15:17:18

vue中監聽滾動事件,然后對其進行事件處理,一般有:1. 滾動到頂部吸附; 2. 根據滾動的位置激活對應的tab鍵(錨鏈接tab鍵)

這兩種方式的處理都是可通過監聽scroll來實現

mounted(){window.addEventListener(’scroll’,this.handleScroll) // 監聽滾動事件,然后用handleScroll這個方法進行相應的處理}處理方法1. 滾動到頂部吸附

html元素

<!--如果isFixed為true的話,就添加class is_fixed 設置固定定位--><div :class='{’is_fixed’ : isFixed}'>這個是要滾動到頂部吸附的元素</div>

methods方法

handleScroll(){let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop // 滾動條偏移量let offsetTop = document.querySelector(’#boxFixed’).offsetTop; // 要滾動到頂部吸附的元素的偏移量this.isFixed = scrollTop > offsetTop ? true : false; // 如果滾動到頂部了,this.isFixed就為true}2. 根據滾動的位置激活對應的tab鍵(錨鏈接tab鍵)

vue里實現錨鏈接,不能直接用a鏈接方式,因為用的是hash路由,直接a鏈接會跳轉路由,可用scrollIntoView ,具體參照 https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView

(1) 實現錨鏈接:

<div v-for='(item,index) in tabs' :class='seeThis==index?’active’:’’'><a href='javascript:void(0)' rel='external nofollow' @click='goAnchor(index)'>{{item}}</a></div><div id='anchor1'>block1</div>

(2) 實現滾動到相應的位置激活tab

data(){return{seeThis:0,tabs:[’tab0’,’tab1’,’tab2’],}},methods:{goAnchor(index) { // 也可以用scrollIntoView方法, 但由于這里頭部設置了固定定位,所以用了這種方法// document.querySelector(’#anchor’+index).scrollIntoView()this.seeThis = index; var anchor = this.$el.querySelector(’#anchor’+index)document.body.scrollTop = anchor.offsetTop-100document.documentElement.scrollTop = anchor.offsetTop-100},}

methods:{handleScroll(){var anchorOffset0 = this.$el.querySelector(’#anchor0’).offsetTop-100var anchorOffset1 = this.$el.querySelector(’#anchor1’).offsetTop-100var anchorOffset2 = this.$el.querySelector(’#anchor2’).offsetTop-100if(scrollTop>anchorOffset0&&scrollTop<anchorOffset1){this.seeThis = 0}if(scrollTop>anchorOffset1&&scrollTop<anchorOffset2){this.seeThis = 1}if(scrollTop>anchorOffset2){this.seeThis = 2}},}

以上就是vue監聽滾動事件的方法的詳細內容,更多關于vue監聽滾動事件的資料請關注好吧啦網其它相關文章!

標簽: Vue
相關文章:
国产综合久久一区二区三区