当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 页面返回上一页浏览位置

页面返回上一页浏览位置

2019年07月03日  | 移动技术网IT编程  | 我要评论

1.如果上一页是静态页面,可以用 history.go(-1)方法;

  go() 方法可加载历史列表中的某个具体的页面。

  该参数可以是数字,使用的是要访问的 url 在 history 的 url 列表中的相对位置。(-1上一个页面,1前进一个页面)。或一个字符串,字符串必须是局部或完整的url,该函数会去匹配字符串的第一个url。

  该方法返回上一页,不刷新页面,但是会执行js;

例子:

<a href="javascript:;" onclick="javascript:history.go(-1);">back</a>

点击back 页面就会返回上一个页面的浏览位置
2.我在工作中遇到的,页面采用了vue,页面每次加载都会去请求数据,用history.go(-1)方法返回上一页,上一页的页面因为重新请求数据,页面不会定位到上次浏览的位置;

解决思路:使用onbeforeunload(事件在即将离开当前页面(刷新或关闭)时触发)方法在页面离开时把滚动条位置和页面文本高度放到cookie中,当页面刷新或重新加载时取出滚动条位置和页面文本高度,设置到页面。

代码如下:

window.onbeforeunload = function () {
var scrollpos, height;
if (typeof window.pageyoffset != 'undefined') {
scrollpos = window.pageyoffset;
} else if (typeof document.compatmode != 'undefined' &&
document.compatmode != 'backcompat') {
scrollpos = document.documentelement.scrolltop;
} else if (typeof document.body != 'undefined') {
scrollpos = document.body.scrolltop;

}
height = document.body.scrollheight;
document.cookie = "scrolltop=" + scrollpos; //存储滚动条位置到cookies中
document.cookie = "height=" + height; //存储滚动条位置到cookies中
}
new vue({
  el:'#app',
  
  updated: function () {
  var height;
  //获取之前的页面高度
  if (document.cookie.match(/height=([^;]+)(;|$)/) != null) {
  var arr = document.cookie.match(/height=([^;]+)(;|$)/); //cookies中不为空,则读取页面高度
  height = parseint(arr[1]);
  }
  //获取之前的滚动条位置
  if (document.body.scrollheight == height) {
   if (document.cookie.match(/scrolltop=([^;]+)(;|$)/) != null) {
  var arr = document.cookie.match(/scrolltop=([^;]+)(;|$)/); //cookies中不为空,则读取滚动条位置
  document.documentelement.scrolltop = parseint(arr[1]);
  document.body.scrolltop = parseint(arr[1]);
  }
  }
  }

})


如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网