移动端详情页返回列表页回滚到原来的位置

介绍

移动端,列表页滚动加载之后,进入详情页,返回列表页之后,自动滚动到之前的位置。
Scroll to same postion when go back to previous page from detail page.

示例地址,在微信里打开即可
示例demo

环境

bootstrap.css 4.1.3
jquery 3.3.1
jquery-weui 1.2.0 # 用于滚动加载
loadingoverlay.js 2.1.7 ## 遮罩

知识点

$.Deferred$.when 配合实现多个 ajax 顺序执行。

示例代码:
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
function _run_ajax_sequential(
ajax_item_list, callback_success,
callback_fail, callback_after_all_call,
callback_fail_after_all_call
) {
// function to trigger the ajax call
let ajax_request = function (item) {
let deferred = $.Deferred();
$.ajax({
url: item['url_str'],
dataType: "json",
type: 'POST',
success: function (data) {
// do something here
if (_isFunction(callback_success)) callback_success(data);
// mark the ajax call as completed
deferred.resolve(data);
},
error: function (error) {
// mark the ajax call as failed
if (_isFunction(callback_fail)) callback_fail(error);
deferred.reject(error);
}
});

return deferred.promise();
};

let looper = $.Deferred().resolve();

// go through each item and call the ajax function
$.when.apply($, $.map(ajax_item_list, function (item, i) {
looper = looper.then(function () {
// trigger ajax call with item data
return ajax_request(item);
});
return looper;
})).then(function () {
// run this after all ajax calls have completed
if (_isFunction(callback_after_all_call)) callback_after_all_call();
return;
//console.log('Done!');
}).fail(function () {
if (_isFunction(callback_fail_after_all_call)) callback_fail_after_all_call();
_loading();
return;
});
}
参数 `ajax_item_list` 如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[
{
"url_str": "http://demo-app.com/ajax_list?page=1&"
},
{
"url_str": "http://demo-app.com/ajax_list?page=2&"
},
{
"url_str": "http://demo-app.com/ajax_list?page=3&"
},
{
"url_str": "http://demo-app.com/ajax_list?page=4&"
},
{
"url_str": "http://demo-app.com/ajax_list?page=5&"
},
{
"url_str": "http://demo-app.com/ajax_list?page=6&"
}
]

应用在 laravel 项目中

项目地址

https://github.com/D0ggy/scroll-to-same-postion

本地运行

php 7.4
composer

克隆到本地:

1
git clone git@github.com:D0ggy/scroll-to-same-postion.git
1
2
3
4
cd scroll-to-same-postion

# 安装扩展
composer install -vvv

运行:

1
php artisan serve

访问:

1
http://127.0.0.1:8000/list

移动端详情页返回列表页回滚到原来的位置
https://hutaoren.cn/2023/01/11/移动端详情页返回列表页回滚到原来的位置/
作者
胡桃仁
发布于
2023年1月11日
许可协议