如何通过LocalStorage实现页面刷新后移除图标保持显示不切换为添加图标
需求说明
我有添加和移除两个图标,页面加载初始默认显示添加图标。具体需求如下:
- 点击添加图标后,切换显示移除图标
- 页面刷新或关闭重新打开后,仍保持显示移除图标
- 只有点击移除图标时,才切换回显示添加图标
完整实现代码
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel='stylesheet' href='https://cdn-uicons.flaticon.com/uicons-regular-rounded/css/uicons-regular-rounded.css'> <link rel='stylesheet' href='https://cdn-uicons.flaticon.com/uicons-solid-rounded/css/uicons-solid-rounded.css'> <title>Fav 1</title> </head> <body> <i onclick="FavId()" class="fi fi-rr-add" id="add"></i> <i onclick="Removefav()" class="fi fi-sr-cross-circle" id="remove"></i> </body> </html>
CSS
body { background-color: black; } i { font-size: 50px; color: white; cursor: pointer; } #remove { display: none; }
JavaScript
// 页面加载时读取本地存储,设置图标初始状态 window.onload = function() { const isFavorited = localStorage.getItem('isFavorited') === 'true'; const addBtn = document.getElementById("add"); const removeBtn = document.getElementById("remove"); if (isFavorited) { addBtn.style.display = "none"; removeBtn.style.display = "block"; } else { addBtn.style.display = "block"; removeBtn.style.display = "none"; } } function FavId() { localStorage.setItem("isFavorited", "true"); const addBtn = document.getElementById("add"); const removeBtn = document.getElementById("remove"); addBtn.style.display = "none"; removeBtn.style.display = "block"; } function Removefav() { localStorage.removeItem("isFavorited"); const removeBtn = document.getElementById("remove"); const addBtn = document.getElementById("add"); removeBtn.style.display = "none"; addBtn.style.display = "block"; }
关键实现说明
- 新增
window.onload事件:页面加载完成后读取localStorage中的状态,根据状态决定显示哪个图标,实现刷新/重启页面后的状态保持 - 在
FavId函数中,通过localStorage.setItem("isFavorited", "true")将收藏状态存入本地存储 - 在
Removefav函数中,通过localStorage.removeItem("isFavorited")移除本地存储的收藏状态 - 给DOM元素变量添加
const声明,避免全局变量污染
内容的提问来源于stack exchange,提问作者Dev.Fra
相关产品推荐
相关产品推荐

