Files

60 lines
1.7 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 页面滚动位置管理工具
* 保存页面滚动位置;主 Tab 切换时回到顶部,子页面返回时保留位置
*/
const SCROLL_POS_KEY = 'tabScrollPositions';
let lastShownTab = '';
/** 主 Tab 的 onShow 调用,兼容底部按钮和代码中的 switchTab。 */
function resetScrollOnTabShow(page, pageKey) {
const switched = lastShownTab !== pageKey;
lastShownTab = pageKey;
if (!switched) return;
const current = page._scrollTop == null ? page.data.scrollTop : page._scrollTop;
page._scrollTop = 0;
saveScrollPosition(pageKey, 0);
if (!current && !page.data.scrollTop) return;
// 手动滚动不会更新绑定的 scrollTop,先同步实际位置再发出回顶指令。
page.setData({ scrollTop: current || page.data.scrollTop }, function() {
page.setData({ scrollTop: 0 });
});
}
/**
* 保存指定页面的滚动位置
* @param {string} pageKey - 页面标识(index/diary/profile)
* @param {number} scrollTop - scroll-view 的滚动位置
*/
function saveScrollPosition(pageKey, scrollTop) {
try {
var positions = wx.getStorageSync(SCROLL_POS_KEY) || {};
positions[pageKey] = {
scrollTop: scrollTop,
timestamp: Date.now()
};
wx.setStorageSync(SCROLL_POS_KEY, positions);
} catch (e) {}
}
/**
* 获取指定页面保存的滚动位置
* @param {string} pageKey - 页面标识
* @returns {number} 保存的 scrollTop,没有则返回 0
*/
function getScrollPosition(pageKey) {
try {
var positions = wx.getStorageSync(SCROLL_POS_KEY) || {};
var pos = positions[pageKey];
return pos ? (pos.scrollTop || 0) : 0;
} catch (e) {
return 0;
}
}
module.exports = {
resetScrollOnTabShow,
saveScrollPosition,
getScrollPosition
};