Vue - 设置锚点,定位到固定位置

1,872 阅读1分钟

Vue - 设置锚点,定位到固定位置

<template>
  <div class="wrap">
    <ul>
      <li><a href="javascript:void(0)" @click="goAuchor('#one')">第一</a></li>
      <li><a href="javascript:void(0)" @click="goAuchor('#two')">第二</a></li>
      <li><a href="javascript:void(0)" @click="goAuchor('#three')">第三</a></li>
      <li><a href="javascript:void(0)" @click="goAuchor('#four')">第四</a></li>
    </ul>
    <div id="one" class="one"></div>
    <div id="two" class="two"></div>
    <div id="three" class="three"></div>
    <div id="four" class="four"></div>
  </div>
</template>

<script>
export default {
  methods:{
    goAuchor(id){
      console.log(id)
      document.querySelector(id).scrollIntoView(true)
      var auchor=this.$el.querySelector(id)
      console.log(auchor)
      console.log(auchor.getBoundingClientRect().top)
      document.body.scrollTop=auchor.offsetTop
    }
  }
};
</script>

<style scoped>
.wrap {
  width: 100%;
  height: 100%;
}
.one{
  width: 100%;
  height: 500px;
  background-color: red;
}
.two{
  width: 100%;
  height: 500px;
  background-color: blue;
}
.three{
  width: 100%;
  height: 500px;
  background-color: green;
}
.four{
  width: 100%;
  height: 500px;
  background-color: yellow;
}
ul{
  width: 100%;
  height: 30px;
  margin: 0;
  padding: 0;
}
li{
  list-style: none;
  float: left;
  background-color: rebeccapurple;
  height: 100%;
  margin-left: 50px;
  cursor: pointer;
}
</style>