vue實現置頂功能


需求背景:項目中需要將某個標題置頂,但element沒有支持置頂的組件,所以手動實現(原生js),效果如下圖:

 

 

 

 

1)解決思路:先找到當前頁面,滾動條所在dom,然后添加滾動條監聽事件,對比滾動條的高度和置頂內容的offsetTop高度,大於則開啟置頂,小於則還原。

2)話不多說上代碼

// 示例代碼
 1 <template>
 2   <div class="main">
 3     <div class="title" :class="isSticky ? 'sticky-title' : '' " :style="{'margin-top': marginTop}">
 4       <div>置頂部分內容</div>
 5     </div>
 6     <div>
 7       <div style="height: 300px;background-color: #6950a1">滾動展現的內容1</div>
 8       <div style="height: 300px;background-color: #6950a1">滾動展現的內容2</div>
 9       <div style="height: 300px;background-color: #6950a1">滾動展現的內容3</div>
10       <div style="height: 300px;background-color: #6950a1">滾動展現的內容4</div>
11       <div style="height: 300px;background-color: #6950a1">滾動展現的內容5</div>
12     </div>
13   </div>
14 </template>
15 <script>
16 let _that = null;
17 
18 export default {
19   name: '',
20   data() {
21     return {
22       curDom: null, // 滾動條節點
23       isSticky: false, // 是否置頂
24       marginTop: 0 // 設置置頂部分外邊距
25     }
26   },
27   mounted(){
28     this.$nextTick(() => {
29       this.stickyEvent();
30     })
31   },
32   methods:{
33     stickyEvent(){
34       _that = this;
35       const myDom = Array.from(document.getElementsByClassName('title'));
36       if (myDom.length) {
37         this.offsetTop = myDom[0].offsetTop; // 置頂內容距離頂部的距離
38       }
39       // 找到滾動條所在節點,很關鍵,否則監聽無效
40       const scrollDom = Array.from(document.getElementsByClassName('el-main'));
41       if (scrollDom.length) {
42         this.curDom = scrollDom[0];
43         // 開啟滾動監聽
44         this.curDom.addEventListener('scroll', this.handleScrollEvent);
45       }
46     },
47     // 滾動監聽事件函數,注意this的指向問題
48     handleScrollEvent(){
49       const scrollTop = _that.curDom.scrollTop; // 滾動條高度
50       if(scrollTop >= _that.offsetTop) {
51         // 開啟置頂,計算位置
52         _that.isSticky = true;
53         _that.marginTop = _that.offsetTop + 'px';
54       } else {
55         _that.isSticky = false;
56         _that.marginTop = 0;
57       }
58     }
59   },
60   destroyed () {
61     // 離開頁面,關閉監聽,釋放資源同時避免報錯
62     this.curDom.removeEventListener('scroll', this.handleScrollEvent);
63   }
64 }
65 </script>
66 <style lang="scss" scoped>
67 .main {
68   width: 100%;
69   min-height: 700px;
70 }
71 // 高度,寬度,背景色根據需求,自行調整
72 .sticky-title {
73   z-index: 999;
74   position: sticky;
75   top: -2%;
76   background: #fff;
77   width: 100%;
78 }
79 </style>

 

 

 只提供一種思路,如果不足之處多多交流指正,如有更好的解決方案,還望不吝指導。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM