LocalStorage 是浏览器提供的持久化存储方案,用于保存少量字符串数据。它支持 setItem、getItem、removeItem 和 clear 等 API,可实现数据的增删查改;只能存储字符串,对象需通过 JSON.stringify 转换;遵循同源策略,容量为 5-10MB;常用于存储用户偏好如主题设置,并可通过安全封装处理异常,但不宜存放敏感信息或大量数据。

HTML5 的 LocalStorage 是一种在浏览器中持久存储数据的简单方式,适合保存少量字符串数据。它不需要请求服务器,页面刷新或关闭后依然保留,非常适合做本地配置、用户偏好或临时缓存。
LocalStorage 有以下几个关键特点:
LocalStorage 提供了几个核心方法来增删查改数据:
保存数据:setItem()使用 localStorage.setItem(key, value) 存入数据,value 必须是字符串。
立即学习“前端免费学习笔记(深入)”;
例如保存用户名称:
localStorage.setItem('username', '张三');如果要保存对象,先用 JSON.stringify() 转换:
const user = { name: '李四', age: 25 };
localStorage.setItem('user', JSON.stringify(user));通过 localStorage.getItem(key) 获取数据,返回字符串或 null(未找到)。
const name = localStorage.getItem('username');
console.log(name); // 输出:张三如果是之前存的对象,需要用 JSON.parse() 还原:
const userData = localStorage.getItem('user');
if (userData) {
const user = JSON.parse(userData);
console.log(user.name); // 输出:李四
}删除指定键的数据:
localStorage.removeItem('username');清空当前域名下的所有 LocalStorage 数据(慎用):
localStorage.clear();
一个常见的使用场景是记住用户的界面主题选择(比如深色/浅色模式)。
HTML 结构:
<button id="theme-toggle">切换主题</button> <div id="app">当前主题将在此显示</div>
JavaScript 实现:
// 获取元素
const app = document.getElementById('app');
const toggleBtn = document.getElementById('theme-toggle');
// 启动时检查是否有保存的主题
const savedTheme = localStorage.getItem('theme') || 'light';
app.className = savedTheme;
// 更新按钮文字
toggleBtn.textContent = savedTheme === 'dark' ? '切换为浅色' : '切换为深色';
// 切换主题函数
function toggleTheme() {
const currentTheme = localStorage.getItem('theme') || 'light';
const newTheme = currentTheme === 'light' ? 'dark' : 'light';
// 更新页面样式
app.className = newTheme;
// 保存到 LocalStorage
localStorage.setItem('theme', newTheme);
// 更新按钮文字
toggleBtn.textContent = newTheme === 'dark' ? '切换为浅色' : '切换为深色';
}
// 绑定点击事件
toggleBtn.addEventListener('click', toggleTheme);
配合简单的 CSS:
#app {
padding: 20px;
transition: background 0.3s;
}
#app.dark {
background: #333;
color: white;
}
#app.light {
background: #f9f9f9;
color: black;
}
这样用户下次打开页面时,会自动加载上次选择的主题。
虽然 LocalStorage 使用方便,但也有几点需要注意:
可以加个安全封装:
function setSafeItem(key, value) {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch (e) {
console.warn('LocalStorage 写入失败:', e);
}
}
function getSafeItem(key) {
try {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : null;
} catch (e) {
console.warn('读取 LocalStorage 失败:', e);
return null;
}
}
基本上就这些。LocalStorage 上手快,适合轻量级本地存储需求,合理使用能显著提升用户体验。
以上就是HTML5怎么使用LocalStorage_HTML5本地存储实战的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号