天天看點

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實作錨點滾動

繼續閱讀