zoukankan      html  css  js  c++  java
  • 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;
        }
      }
  • 相关阅读:
    MySQL Thread Pool: Problem Definition
    MySQL数据库InnoDB存储引擎多版本控制(MVCC)实现原理分析
    Mysql源码目录结构
    android学习18——对PathMeasure中getPosTan的理解
    android学习17——命令行建gradle工程
    android学习16——library project的使用
    android学习13——android egl hello world
    ant编译java的例子
    android学习12——重载SurfaceView一些方法的执行顺序
    Visual Studio命令行创建库文件lib
  • 原文地址:https://www.cnblogs.com/fairy-0518/p/12858057.html
Copyright © 2011-2022 走看看