Vue项目通过scrollIntoView实现锚点滚动

实现代码

goAnchor(selector) {
  this.$el.querySelector(selector).scrollIntoView({
      behavior: "smooth",  // 平滑过渡
      block:    "start"  // 上边框与视窗顶部平齐。默认值
  });
}

scrollIntoView

参考: https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView


完整示例代码

<template>
  <div class="main">
    <!-- 菜单 -->
    <div class="nav">
      <a href="javascript:" @click="goAnchor('#Java')">Java</a>
      <a href="javascript:" @click="goAnchor('#Python')">Python</a>
      <a href="javascript:" @click="goAnchor('#Javascript')">Javascript</a>
    </div>

    <!-- 内容 -->
    <div class="item">
      <div class="title" id="Java">Java</div>
      <div class="content"></div>
    </div>

    <div class="item">
      <div class="title" id="Python">Python</div>
      <div class="content"></div>
    </div>

    <div class="item">
      <div class="title" id="Javascript">Javascript</div>
      <div class="content"></div>
    </div>
  </div>

</template>

<script>
export default {
  methods: {
    // 标签滚动
    goAnchor(selector) {
      this.$el.querySelector(selector).scrollIntoView({
          behavior: "smooth",  // 平滑过渡
          block:    "start"  // 上边框与视窗顶部平齐。默认值
      });
    }
  }
};
</script>

<style scoped>
.main {
  width: 600px;
  margin: 0 auto;
  margin-top: 20px;
}

.nav a {
  text-decoration: none;
  color: #333;
  padding: 0 10px;
  margin: 0 5px;
  background: #9e9e9e;
  line-height: 2;
}

.nav {
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.item{
    margin-top: 20px;
}

.title{
    background: #9e9e9e;
    line-height: 2;
}
.content {
  height: 300px;
  background: #eeeeee;
}
</style>

Vue项目通过scrollIntoView实现锚点滚动

上一篇:第一章:JAVA项目工程化之项目构建工具maven


下一篇:带你读《果壳中的5G:新网络时代的技术内涵与商业思维》第一章从 0 到 5 的演化与逻辑1.5(二)