JS返回页面时自动回滚到历史浏览位置

在个人系统实际开发过程当中遇到一个需求,我须要让应用在各个页面间跳转时回到每页原先浏览到的位置,方便用户使用。前端

在网上查资料时,看到的方案有很多,众说纷纭,但真正给出可行可用代码的寥寥无几,因此我干脆按本身的想法用SessionStorage写了一个缓存页面的方法,在离开页面时将须要缓存的容器中全部内容都存到SessionStorage中,在返回页面时从新加载,方便用户操做,效果以下:缓存

前端精品教程:百度网盘下载session

页面缓存ui

前端精品教程:百度网盘下载spa

使用方法.net

用法也很简单,咱一步一步讲。code

首先,在你须要缓存标签容器的类名中加入cache,并写一个name做为该容器的惟一标记,示例以下:htm

?
1
2
3
<div class= "weui-tab cache" name= "index" >
  ....
</div>

其次,声明全局变量,获取缓存内容和容器,示例以下:教程

?
1
2
var cache;
var cacheId = $( ".cache" ).attr( "name" );

随后,在页面加载时调用缓存,在离开页面时生成缓存,代码以下:ip

前端精品教程:百度网盘下载

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
window.onload = function () {
  //载入缓存的列表
  loadCache(cacheId);
}
 
window.onunload = function () {
  //能够经过needCache这个flag来控制是否须要缓存
  if (localStorage.needCache == 'true' ) {
   //离开页面时生成缓存
   createCache(cacheId);
  }
}
 
/* *
  * @brief 可对指定多个控件进行内容和位置的缓存
  * @param cacheId 缓存元素的id
  * @return null
  * */
function createCache(cacheId) {
  //对内容进行缓存
  var list = [];
  var listController = $( '.cache' );
  $.each(listController, function (index, value, array) {
   list.push(value.innerHTML);
  })
  //对浏览到的位置进行缓存
  var top = [];
  var topController = $( ".cache" ).find( ".top" );
  $.each(topController, function (index, value, array) {
   top.push(value.scrollTop);
  })
  //存入sessionstorage中
  sessionStorage.setItem(cacheId, JSON.stringify({
   list: list,
   top: top
  }));
}
 
/* *
  * @breif 可对指定多个控件加载缓存
  * @param 加载缓存的id
  * @return null
  * */
function loadCache(cacheId) {
  //必定要放在整个js文件最前面
  cache = sessionStorage.getItem(cacheId);
  if (cache) {
   cache = JSON.parse(cache);
   //还原内容
   var listController = $( '.cache' );
   $.each(listController, function (index, value, array) {
    value.innerHTML = cache.list[index];
   })
   //还原位置
   var topController = $( ".cache" ).find( ".top" );
   $.each(topController, function (index, value, array) {
    value.scrollTop = cache.top[index];
   })
  }
}

大部分均可以直接copy,再根据你的须要改进一下,就能够很好的使用了。

相关文章
相关标签/搜索