如何使用localStorage保存选中文本至新div?JS新手开发者求助
嘿,作为JavaScript新手别发愁,我帮你把这个文本保存功能完整实现出来,还会把每一步的逻辑给你讲明白,代码直接就能用~
完整实现代码
HTML文件(index.html)
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>保存选中文本</title> <link rel="stylesheet" href="style.css"> </head> <body> <!-- 可选择文本的区域 --> <div class="content"> 这里是可以选中的文本内容,试试选中一段文字,然后点击下面的按钮保存吧!<br> 比如这段:JavaScript是一门强大的脚本语言,适合前端开发。<br> 还有这段:localStorage可以帮我们在浏览器中持久化存储数据,即使关闭页面也不会丢失。 </div> <!-- 保存按钮 --> <button id="saveBtn">保存选中的文本</button> <!-- 保存结果展示区域 --> <div class="saved-area"> <h3>已保存的文本:</h3> <div id="savedContent"></div> </div> <script src="script.js"></script> </body> </html>
CSS文件(style.css)
.content { padding: 20px; border: 1px solid #eee; margin-bottom: 20px; line-height: 1.6; } #saveBtn { padding: 8px 16px; background-color: #4CAF50; color: white; border: none; cursor: pointer; margin-bottom: 20px; } #saveBtn:hover { background-color: #45a049; } .saved-area { padding: 20px; border: 1px solid #ddd; background-color: #f9f9f9; } #savedContent { margin-top: 10px; padding: 10px; background-color: white; border: 1px solid #eee; min-height: 50px; }
JavaScript文件(script.js)
// 获取DOM元素 const saveBtn = document.getElementById('saveBtn'); const savedContent = document.getElementById('savedContent'); // 页面加载时,从localStorage恢复已保存的文本 window.addEventListener('DOMContentLoaded', () => { const savedText = localStorage.getItem('savedSelectedText'); if (savedText) { savedContent.textContent = savedText; } }); // 点击按钮保存选中的文本 saveBtn.addEventListener('click', () => { // 获取用户选中的文本,兼容现代浏览器和旧版IE let selectedText = ''; if (window.getSelection) { selectedText = window.getSelection().toString(); } else if (document.selection && document.selection.type != 'Control') { selectedText = document.selection.createRange().text; } // 验证是否有选中的文本 if (selectedText.trim() !== '') { // 更新页面展示区域 savedContent.textContent = selectedText; // 存入localStorage持久化保存 localStorage.setItem('savedSelectedText', selectedText); alert('文本已成功保存!'); } else { alert('请先选中一段文本哦~'); } }); // 额外保障:浏览器关闭/刷新前确保数据已存储(其实上面的setItem已经实时保存了,这里是双重保险) window.addEventListener('beforeunload', () => { const currentText = savedContent.textContent; if (currentText.trim() !== '') { localStorage.setItem('savedSelectedText', currentText); } });
功能逻辑拆解
- 获取选中文本:用
window.getSelection()处理现代浏览器的选中文本,同时兼容旧版IE的document.selection,确保绝大多数浏览器都能正常工作。 - 实时展示保存内容:点击按钮后,把选中的文本直接赋值给展示区域的
textContent,用户能立刻看到保存的结果。 - localStorage持久化:通过
localStorage.setItem()把文本存在浏览器本地,这个数据会一直保留,除非用户手动清除浏览器缓存或者你调用localStorage.removeItem('savedSelectedText')删除它。 - 页面加载自动恢复:监听
DOMContentLoaded事件,页面加载完成后立刻从localStorage读取之前保存的文本,展示到指定区域,这样刷新页面、关闭浏览器再打开都能看到之前保存的内容。 - 友好交互提示:如果用户没选中文本就点按钮,会弹出提示引导用户;保存成功也会有反馈,提升整体体验。
内容的提问来源于stack exchange,提问作者ApolloBear
相关产品推荐
相关产品推荐

