vue实现锚点定位平滑滚动

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue实现锚点定位平滑滚动

寸头强   2022-09-29 我要评论

vue锚点定位平滑滚动

下面是简单的代码,拿来即用

html 

//给div盒子设定单击事件和ref名
<div @click="getThere" ref="cat_box">点击滑动到此位置</div>
methods: {
 getThere() {
      // 通过ref名获取元素在页面中的位置并滚动至此
      this.$el.querySelector(".cat_box")
      .scrollIntoView({ block: "start", behavior: "smooth" });  
    },
}

vue点击tabs平滑滚动(锚点事件)

避免切换速度过快显得突兀,在不使用 a 标签以及添加 class类 进行锚点操作时,这时候就可以用到 dom 方法 scrollTo 来实现平滑滚动。

定义

scrollTo(xpos,ypos),包含两个必须属性

  • xpos(指定滚动到X轴指定位置)
  • ypos(指定滚动到X轴指定位置)

使用:

// 滚动到指定位置window.scrollTo(100,500)

scrollTo(options),包含三个必须属性

  • top (y-coord) 相当于y轴指定位置
  • left (x-coord) 相当于x轴指定位置
  • behavior 类型String,表示滚动行为,支持参数 smooth(平滑滚动),instant(瞬间滚动),默认值auto

使用:

// 设置滚动行为改为平滑的滚动
window.scrollTo({
    top: 1000,
    behavior: "smooth"
});

兼容

适用于pc端和移动端,scrollTo(options)属性不兼容 IE

在这里插入图片描述

使用

// vue中使用
// 标题
<div
   class="tabs"
   v-for="(item, index) in titAll"
   :key="index"
   :class="{ actives: isactive === index }"
   @click="tabsColor(index)"
>
     {{ item }}
</div>
// 分类tit
<div>
  <div class="item" id="tabs0">资产账户</div>
  // <div>分类内容</div>
  <div class="item" id="tabs1">信贷服务</div>
  // <div>分类内容</div>
  <div class="item" id="tabs2">金融服务</div>
  // <div>分类内容</div>
</div>
 data() {
   return {
     titAll: ["资产账户", "信贷金融", "经融服务"],
     //初始选中
     isactive: 0,
   };
 },
 methods: {
  tabsColor(index) {
  	// 切换选中样式
    this.isactive = index;
    // 获取对应iddom
    const tabsId = document.querySelector(`#tabs${index}`);
    // 判断进行平滑滚动
    if (tabsId) {
      window.scrollTo({
        top: tabsId.offsetTop,
        behavior: "smooth",
      });
    }
  },
},

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们