页面刷新后如何保持ul元素内的水平滚动位置
问题描述
我实现了一个用于展示商品变体选项、支持水平滚动的ul列表。实际使用中存在如下问题:滚动列表后点击任意变体选项会触发页面刷新,刷新完成后列表的滚动位置会重置到初始起点。现需要实现页面刷新后,列表仍能保留刷新前滚动位置的效果。
现有代码
CSS样式
ul#group_17 { width: 150px; display: flex; overflow: auto; list-style: none; } li {margin: 0 10px 0 0} .input-color { position: absolute; opacity: 0; cursor: pointer; height: 60px; width: 60px; } span { height: 60px; width: 60px; display: block; }
HTML结构
<ul id="group_17"> <li class="float-xs-left input-container"> <label> <input class="input-color" type="radio" data-product-attribute="17" name="group[17]" value="87"> <span class="color texture" style="background:black"></span> </label> </li> <li class="float-xs-left input-container"> <label> <input class="input-color" type="radio" data-product-attribute="17" name="group[17]" value="88" checked="checked"> <span class="color texture" style="background:brown;"></span> </label> </li> <li class="float-xs-left input-container"> <label> <input class="input-color" type="radio" data-product-attribute="17" name="group[17]" value="89"> <span class="color texture" style="background:red"></span> </label> </li> <li class="float-xs-left input-container"> <label> <input class="input-color" type="radio" data-product-attribute="17" name="group[17]" value="90"> <span class="color texture" style="background:yellow"></span> </label> </li> </ul>
实现方案
核心逻辑是通过浏览器本地存储暂存列表的滚动位置,页面刷新后读取存储值恢复位置,不需要改动现有CSS和HTML结构,只需要新增一段JavaScript代码即可。
- 存储逻辑:在页面刷新/关闭前,获取列表的水平滚动距离(
scrollLeft属性),存入sessionStorage。 - 恢复逻辑:页面DOM加载完成后,读取存储的滚动距离,将列表滚动到对应位置。
基础实现代码如下:
// 获取目标变体列表元素 const variantList = document.getElementById('group_17'); // 定义存储key,和元素绑定避免和其他页面数据冲突 const SCROLL_STORAGE_KEY = 'group_17_scroll_position'; // 页面DOM加载完成后恢复滚动位置 window.addEventListener('DOMContentLoaded', () => { const savedPosition = sessionStorage.getItem(SCROLL_STORAGE_KEY); if (savedPosition !== null) { variantList.scrollLeft = Number(savedPosition); } }); // 页面卸载前保存当前滚动位置 window.addEventListener('beforeunload', () => { sessionStorage.setItem(SCROLL_STORAGE_KEY, variantList.scrollLeft); });
如果需要更高的可靠性,避免极端场景下beforeunload事件未触发导致存储失败,可以新增实时滚动监听,滚动过程中同步更新存储值,加了passive: true配置不会影响页面滚动性能:
// 可选:实时同步滚动位置到存储 variantList.addEventListener('scroll', () => { sessionStorage.setItem(SCROLL_STORAGE_KEY, variantList.scrollLeft); }, { passive: true });
说明:选择
sessionStorage而非localStorage是因为前者仅在当前标签页生效,关闭标签页后自动清除数据,不会长期占用本地存储,也不会影响用户下次打开商品页的初始浏览状态。
内容的提问来源于stack exchange,提问作者Enrico
相关产品推荐
相关产品推荐

