码迷,mamicode.com
首页 > 其他好文 > 详细

页面跳转,A跳到B,B再返回A时自动定位到离开A时的位置

时间:2018-07-01 19:02:34      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:temp   scrollto   template   aaa   att   outer   页面跳转   自动   ||   

 

<template>
  <div class="hello"  @scroll="scrollLoad" id="myScrollBox">
    <h1>{{ msg }}</h1>
    <ul>
      <li class="my-li">aaaaaaaaa</li>
      <li class="my-li">aaaaaaaaa</li>
      <li class="my-li">aaaaaaaaa</li>
      <li class="my-li">aaaaaaaaa</li>
      <li class="my-li">aaaaaaaaa</li>
      <li class="my-li">aaaaaaaaa</li>
      <li class="my-li">aaaaaaaaa</li>
      <li class="my-li">aaaaaaaaa</li>
      <li class="my-li">aaaaaaaaa</li>
      <li class="my-li">aaaaaaaaa</li>
    </ul>
    <button @click="goForward">go 2</button>
    <ul>
      <li class="my-li">aaaaaaaaa</li>
      <li class="my-li">aaaaaaaaa</li>
      <li class="my-li">aaaaaaaaa</li>
      <li class="my-li">aaaaaaaaa</li>
      <li class="my-li">aaaaaaaaa</li>
      <li class="my-li">aaaaaaaaa</li>
      <li class="my-li">aaaaaaaaa</li>
      <li class="my-li">aaaaaaaaa</li>
      <li class="my-li">aaaaaaaaa</li>
      <li class="my-li">aaaaaaaaa</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      msg: "this is hello 1 !",
      lengthToTop: 0
    };
  },

  beforeRouteLeave(to, from, next) {
    this.recordViewPortPosition();
    next();
  },

  mounted: function() {
    this.setViewPortPosition();
  },

  methods: {
    goForward: function() {
      this.$router.push("h2");
    },

    // 获得距离顶部的位置,暂存一个变量里
    // 本方法配合recordViewPortPosition、setViewPortPosition使用
    scrollLoad: function() {
      let box = document.getElementById("myScrollBox");
      this.lengthToTop = box.scrollTop;
    },

    // 离开首页时记录距离顶部的位置,存到sessionStorage里,方便回来时取用
    recordViewPortPosition: function() {
      sessionStorage.lengthToTop = this.lengthToTop;
    },

    // 离开首页再返回时,重新定位到离开时的位置
    setViewPortPosition: function() {
      let lengthToTop = sessionStorage.lengthToTop;
      if (lengthToTop === null || lengthToTop === undefined) {
        lengthToTop = 0;
      }
      document.getElementById("myScrollBox").scrollTop = lengthToTop; // 距离顶部100px就直接写scrollTop = 100, 不要写100+“px”
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.hello {
  position: absolute;
  width: 100%;
  height: 100%;
  overflow: scroll;
}
li {
  display: block;
  height: 100px;
  width: 300px;
  border: 1px solid #000;
  font-size: 15px;
}
</style>

 

页面跳转,A跳到B,B再返回A时自动定位到离开A时的位置

标签:temp   scrollto   template   aaa   att   outer   页面跳转   自动   ||   

原文地址:https://www.cnblogs.com/longxia777/p/9250764.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!