vue 利用原生滚动监听tabs亮显

11 篇文章 0 订阅

1、html

tabs

对应监听模块

<div class="scroll-item" ref="content2">1</div>
<div class="scroll-item" ref="content2">2</div>
<div class="scroll-item" ref="content2">3</div>
<div class="scroll-item" ref="content2">4</div>

2、js


mounted() {
  document.onscroll = (e) => {
      this.scrollNav(document.querySelectorAll('.scroll-item'));
  };
},
//方法
methods:{
    scrollNav(sections) {
            const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; // 滚动条偏移量
            sections.forEach((item, index) => {
                if (item.offsetTop - 100 <= scrollTop) {
                    this.activeTabIndex = index; //根据这个index给固定tabs的item赋值
                }
            });
            // 假设最后一个滚动内容高度不够时滚动条到底部默认亮显示最后一个tab
            // 变量windowHeight是可视区的高度
            const windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
            // 变量scrollHeight是滚动条的总高度
            const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
            // 滚动条到底部的条件
            if (scrollTop + windowHeight === scrollHeight) {
                this.activeTab = this.navList[this.navList.length - 1];
            }
        },
}

3、点击tabs到对应位置可以使用

//tab值是scorll-item的ref值
this.$refs[tab].scrollIntoView({ block: 'start', behavior: 'smooth' });

粗略记录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值