Vue中快速实现点击侧导航页面平滑到需要的位置

先看效果:

实现侧导航第一步肯定是控制侧导航的显示隐藏,然后通过点击事件回到需要的位置,而这个位置我不希望它写死距离,就可以用到描点的方式来实现了。控制描点元素位置来实现内容变化还是滑动在想要的位置。但是直接使用描点不会具有平滑效果,其实浏览器原生提供了一种方法scrollIntoView ,它可以操作元素滚动到可视区域内,而且可以在后面添加滚动的效果。

如果需要实现回到顶部那可以将描点元素写在页面顶部然后通过 transform: translateY();实现平移到页面最顶部且看不到的区域,这样使用scrollIntoView 来将顶部元素滚动到可视区域就等同于页面滚动到最顶部来实现回到顶部功能。

需要滚动到可视区域的元素.scrollIntoView({ behavior: "smooth" });

后面可以通过 behavior: "smooth"来指定滚动方式为平滑效果。

以下是示例的完整代码:

<template>
  <div class="hello">
    <!-- 回到顶部描点 -->
    <div class="goback-top" ref="goBackTop"></div>
    <!-- 回到顶部按钮 -->
    <div class="goback" v-show="isShowGoTop" @click="scrollTop">回到顶部</div>
    <h1>{{ name }}</h1>
    <div class="container">
      <ul>
        <li
          v-for="(item, index) in bgcList"
          :key="index"
          :style="{ backgroundColor: item }"
        ></li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      name: "我是标题",
      isShowGoTop: false,
      bgcList: [
        "pink",
        "skyblue",
        "orange",
        "pink",
        "skyblue",
        "orange",
        "pink",
        "skyblue",
        "orange",
      ],
    };
  },
  methods: {
    // 监听滚动事件使回到顶部显示隐藏
    handleScroll() {
      const scrollHeight = window.scrollY; //获取页面滚动卷去的高度
      // 处理滚动高度
      this.isShowGoTop = scrollHeight >= 350 ? true : false;
    },
    // 点击回到顶部
    scrollTop() {
      const goBackTop = this.$refs.goBackTop;
      goBackTop.scrollIntoView({ behavior: "smooth" });
    },
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.goback-top {
  transform: translateY(-200px);
}
.container {
  height: 200vh;
}
.goback {
  z-index: inherit;
  padding: 10px;
  position: fixed;
  width: 30px;
  height: 40px;
  right: 50px;
  bottom: 200px;
  font-size: 14px;
  background-color: black;
  color: white;
  cursor: pointer;
}
li {
  list-style: none;
  height: 100px;
}
</style>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

识海.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值