vue中監聽滾動事件,然后對其進行事件處理,一般有:1. 滾動到頂部吸附; 2. 根據滾動的位置激活對應的tab鍵(錨鏈接tab鍵)
這兩種方式的處理都是可通過監聽scroll來實現
1
2
3
|
mounted(){ window.addEventListener( 'scroll' , this .handleScroll) // 監聽滾動事件,然后用handleScroll這個方法進行相應的處理 } |
處理方法
1. 滾動到頂部吸附
html元素
1
2
3
4
|
<!--如果isFixed為true的話,就添加class is_fixed 設置固定定位--> < div id = "boxFixed" :class = "{'is_fixed' : isFixed}" > 這個是要滾動到頂部吸附的元素 </ div > |
methods方法
1
2
3
4
5
|
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) 實現錨鏈接:
1
2
3
|
< div class = "flexitem" 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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-100 document.documentElement.scrollTop = anchor.offsetTop-100 }, } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
methods:{ handleScroll(){ var anchorOffset0 = this .$el.querySelector( '#anchor0' ).offsetTop-100 var anchorOffset1 = this .$el.querySelector( '#anchor1' ).offsetTop-100 var anchorOffset2 = this .$el.querySelector( '#anchor2' ).offsetTop-100 if (scrollTop>anchorOffset0&&scrollTop<anchorOffset1){ this .seeThis = 0 } if (scrollTop>anchorOffset1&&scrollTop<anchorOffset2){ this .seeThis = 1 } if (scrollTop>anchorOffset2){ this .seeThis = 2 } }, } |
以上就是vue監聽滾動事件的方法的詳細內容,更多關于vue監聽滾動事件的資料請關注服務器之家其它相關文章!
原文鏈接:https://www.cnblogs.com/nbwsj/p/12122689.html