HTML页面重载后如何让标记盒子保持在已保存的阅读位置
解决方案
问题原因
- 你的代码仅存储了滚动位置的百分比,未将标记盒子的偏移位置、跳转按钮的显示状态做持久化存储
- 页面重载后临时变量
cordinateCont、cordinateBtn会被清空,也没有主动给标记盒子重新赋值位置,所以盒子会回到初始的0位置
具体修改步骤
1. 完善存储逻辑,新增盒子位置存储
修改两个保存函数,同步存储标记盒子的top值:
function saveInStorage() { const scrollPercent = document.documentElement.scrollTop / getTotalHeight(); const boxTop = cordinateCont + 60 - cordinateBtn; localStorage.setItem("scrollPercent", scrollPercent); localStorage.setItem("boxTop", boxTop); // 新增存储盒子位置 } function saveCookie() { const expDate = new Date(); expDate.setDate(expDate.getDate() + 7); const scrollPercent = document.documentElement.scrollTop / getTotalHeight(); const boxTop = cordinateCont + 60 - cordinateBtn; // 新增boxTop到cookie document.cookie = `scrollPercent=${scrollPercent}; boxTop=${boxTop}; expires=${expDate.toUTCString()}`; }
2. 新增加载盒子位置的逻辑
补充对应的读取方法:
function getSavedBoxTop() { var boxTop = storageSupported ? localStorage.getItem("boxTop") : document.cookie.replace(/(?:(?:^|.*;\s*)boxTop\s*\=\s*([^;]*).*$)|^.*$/, "$1"); return (boxTop == null || boxTop == "") ? 0 : Number(boxTop); }
3. 页面重载时恢复盒子位置和按钮显示
修改页面初始化的逻辑:
var storageSupported = checkStorageSupport(), percent = getSavedPercent(), savedBoxTop = getSavedBoxTop(); // 读取存储的盒子位置 if (percent > 0) { if (confirm("Would you like to continue reading where you left off?")) { document.documentElement.scrollTop = percent * getTotalHeight(); // 新增:恢复盒子位置和跳转按钮显示 boxMove.style.top = savedBoxTop + 'px'; takeMeToSave.style.display = "block"; }; }
4. 补全缺失的函数声明(原代码存在语法问题)
你原代码开头的存储检测逻辑漏了函数声明,需要补上:
function checkStorageSupport() { // 补全函数名 var test = "test"; try { localStorage.setItem(test, test); localStorage.removeItem(test); return true; } catch(e) { return false; } }
内容的提问来源于stack exchange,提问作者Wickeda
相关产品推荐
相关产品推荐

