如何将网页选择的字体大小存储到localStorage,刷新后保留设置?
用localStorage保留字体大小设置,解决刷新后恢复默认的问题
当然可以用localStorage来保存用户选择的字体大小,刷新页面后自动恢复设置。下面是修改后的完整代码,我调整了事件处理逻辑,把内联点击事件移到JS里,同时加入localStorage的读写逻辑:
修改后的HTML
<section class="sec"> <div class="content"> <div class="buttons"> <span class="btn clicked" data-font-size="1em">A</span> <span class="btn" data-font-size="1.25em">A</span> <span class="btn" data-font-size="1.75em">A</span> </div> <div class="text" id="text"> <h3>i'm an h3</h3> <p>i'm a paragraph</p> </div> </div> </section>
修改后的CSS(无需改动,保持原样式)
:root { --secondary-color: #4978ff; } .sec .buttons { width: 100%; display: flex; justify-content: flex-end; align-items: flex-end; margin-bottom: 20px; } .sec .buttons .btn { padding: 0 10px; display: inline-flex; background: #ddd; color: var(--primary-color); margin-left: 10px; cursor: pointer; } .sec .buttons .btn.clicked { background: var(--secondary-color); } .sec .buttons .btn:nth-child(2) { font-size: 1.5em; } .sec .buttons .btn:nth-child(3) { font-size: 2em; }
修改后的JavaScript
const textElement = document.getElementById('text'); const buttonsContainer = document.querySelector('.buttons'); const buttons = buttonsContainer.querySelectorAll('.btn'); // 页面初始化时加载保存的字体大小 function initFontSize() { const savedSize = localStorage.getItem('fontSize'); const defaultSize = '1em'; const targetSize = savedSize || defaultSize; // 设置文本字体大小 textElement.style.fontSize = targetSize; // 标记对应的按钮为选中状态 buttons.forEach(btn => { if (btn.dataset.fontSize === targetSize) { btn.classList.add('clicked'); } else { btn.classList.remove('clicked'); } }); } // 绑定按钮点击事件 buttons.forEach(btn => { btn.addEventListener('click', function() { // 移除所有按钮的选中状态 buttons.forEach(b => b.classList.remove('clicked')); // 标记当前按钮为选中 this.classList.add('clicked'); // 获取当前按钮对应的字体大小 const fontSize = this.dataset.fontSize; // 设置文本字体大小 textElement.style.fontSize = fontSize; // 保存到localStorage localStorage.setItem('fontSize', fontSize); }); }); // 页面加载完成后初始化 document.addEventListener('DOMContentLoaded', initFontSize);
关键改动说明
- HTML部分:移除了内联
onclick属性,改用data-font-size存储字体大小值,让代码结构更清晰,也便于后续扩展更多字体选项。 - JavaScript部分:
- 新增
initFontSize函数,在页面加载时读取localStorage中的设置,自动恢复上次选择的字体大小,并同步按钮选中状态。 - 统一管理按钮点击事件,点击时不仅切换选中样式,还将所选字体大小存入
localStorage,确保刷新后设置不丢失。
- 新增
内容的提问来源于stack exchange,提问作者Pascal
相关产品推荐
相关产品推荐

