vue滑動吸頂以及錨點定位


Vue項目中需要實現滑動吸頂以及錨點定位功能。template代碼如下:

<template>
<div class="main">
    <div id='menu'>
        <ul>
            <li v-for="item in tabList" @click='clickTab'></li>
        </ul>
    </div>
    <div id='div1'></div>
    <div id='div2'></div>
    <div id='div3'></div>
</div>  
</template>

(1)滑動吸頂:

監聽scroll事件,獲取頁面的滾動距離,一旦滾動距離大於目標值,實現滑動吸頂功能。

public isFixed = false;
public mounted() {
    this.menuTop = (document.getElementById('menu') as any).offsetTop;
    window.addEventListener('scroll', this.handleScroll);
 }
public handleScroll() {
    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop; // 獲取滑動距離
    if (scrollTop < this.menuTop ) {
      this.isFixed = false;
    } else {
      this.isFixed = true; // 設置fixed定位
    }
 }
public destroyed() {
    window.removeEventListener('scroll', this.handleScroll);
}

(2)錨點定位。點擊tab,設置頁面滾動距離。

public clickTab(index: number) {
    this.activeIndex = index;
    this.isFixed = true;
    const menuHeight= (document.getElementById('menu') as any).offsetHeight;
    const div1= (document.getElementById('div1') as any).offsetTop;
    const div2= (document.getElementById('div2') as any).offsetTop;
    const div3= (document.getElementById('div3') as any).offsetTop;
    const div4= (document.getElementById('div4') as any).offsetTop;
    switch (index) {
      case 0: document.body.scrollTop = document.documentElement.scrollTop = div1 - menuHeight; break;
      case 1: document.body.scrollTop = document.documentElement.scrollTop = div2 - menuHeight; break;
      case 2: document.body.scrollTop = document.documentElement.scrollTop = div3 - menuHeight; break;
      case 3: document.body.scrollTop = document.documentElement.scrollTop = div4 - menuHeight; break;
      default: document.body.scrollTop = document.documentElement.scrollTop = div1- menuHeight;
    }
  }


免責聲明!

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



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