如何获取contenteditable为true的fieldset值并实现本地存储存读?
问题描述
我有一个设置了contenteditable="true"的<fieldset>元素,想要实现两个功能:
- 点击保存按钮,将
<fieldset>的内容存入localStorage - 点击加载按钮,从
localStorage取出内容回填到<fieldset>中
但当前代码无法正常工作,点击保存后控制台打印localStorage中的值显示为undefined。
原HTML代码
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Editor</title> <link rel="stylesheet" href="index.css" /> </head> <body> <div class="buttons"> <button class="bold" onclick="document.execCommand('bold',false,null);" title="Bold" > 𝗕 </button> <button class="italic" onclick="document.execCommand('italic',false,null);" title="Italic" > 𝘐 </button> <button class="underline" onclick="document.execCommand('underline',false,null);" title="Underline" > U̲ </button> <input type="color" class="color-picker" id="colorPicker" oninput="changeColorText(this.value);" title="Change text color" /> <button id="highlight"><mark>A</mark></button> <button id="bulletPoint">•</button> <!-- Make something to change the font size --> <button id="fontSize" onclick="changeFont()">Change</button> <input type="number" id="fontInput" placeholder="Size" /> <select id="fontList"> <option value="Arial">Arial</option> <option value="Comic Sans MS">Comic Sans MS</option> <option value="Courier New">Courier New</option> <option value="Georgia">Georgia</option> <option value="Helvetica">Helvetica</option> <option value="Impact">Impact</option> <option value="Lucida Console">Lucida Console</option> <option value="Lucida Sans Unicode">Lucida Sans Unicode</option> <option value="Palatino Linotype">Palatino Linotype</option> <option value="Tahoma">Tahoma</option> <option value="Times New Roman">Times New Roman</option> <option value="Trebuchet MS">Trebuchet MS</option> <option value="Verdana">Verdana</option> </select> </div> <!-- Make a button to save the text in local storage when clicked --> <button id="save">Save</button> <!-- Make a button to load the text from localstorage --> <button id="load">Load</button> <fieldset class="userInput" contenteditable="true"></fieldset> <script src="use.js"></script> </body> </html>
原JavaScript代码
var boldBtn = document.querySelector(".bold"); var italicBtn = document.querySelector(".italic"); var underlineBtn = document.querySelector(".underline"); var colorPicker = document.querySelector(".color-picker"); var highlightBtn = document.querySelector("#highlight"); var bulletPointBtn = document.querySelector("#bulletPoint"); var fontSize = document.querySelector("#fontSize"); var fontInput = document.querySelector("#fontInput"); var fontList = document.querySelector("#fontList"); var saveBtn = document.querySelector("#save"); var userInput = document.querySelector(".userInput"); var loadBtn = document.querySelector("#load"); boldBtn.addEventListener("click", function () { boldBtn.classList.toggle("inUse"); }); italicBtn.addEventListener("click", function () { italicBtn.classList.toggle("inUse"); }); underlineBtn.addEventListener("click", function () { underlineBtn.classList.toggle("inUse"); }); highlightBtn.addEventListener("click", function () { highlightBtn.classList.toggle("inUse"); }); const changeColorText = (color) => { document.execCommand("styleWithCSS", false, true); document.execCommand("foreColor", false, color); }; document.getElementById("highlight").addEventListener("click", function () { var range = window.getSelection().getRangeAt(0), span = document.createElement("span"); span.className = "highlight"; span.appendChild(range.extractContents()); range.insertNode(span); }); //Add a bullet point using the html tag <ul> when the user clicks on the bullet point button bulletPointBtn.addEventListener("click", function () { document.execCommand("insertHTML", false, "<ul><li> </li></ul>"); }); function changeFont() { document.execCommand("fontSize", false, "7"); var fontElements = document.getElementsByTagName("font"); for (var i = 0, len = fontElements.length; i < len; ++i) { if (fontElements[i].size == "7") { fontElements[i].removeAttribute("size"); fontElements[i].style.fontSize = fontInput.value + "px"; } } } // Make the font whatever the user selects from the dropdown menu fontList.addEventListener("change", function () { document.execCommand("fontName", false, fontList.value); }); // When the user clicks the save button, save the text from the fieldset to local storage saveBtn.addEventListener("click", function () { localStorage.setItem("userInput", userInput.value); console.log(localStorage.getItem("userInput")); }); //When the user clicks the load button, load the text from local storage to the fieldset and display it if it exists loadBtn.addEventListener("click", function () { if (localStorage.getItem("userInput")) { userInput.value = localStorage.getItem("userInput"); } });
问题原因
contenteditable元素不属于表单控件(如<input>、<textarea>),不能通过.value属性获取或设置内容。这类元素的内容需要用.innerHTML(保留富文本格式)或.textContent(仅纯文本)来操作。
修正后的代码
只需修改保存和加载按钮的事件处理逻辑,替换为.innerHTML即可:
修正后的JavaScript核心代码
// 保存按钮事件 saveBtn.addEventListener("click", function () { localStorage.setItem("userInput", userInput.innerHTML); console.log(localStorage.getItem("userInput")); }); // 加载按钮事件 loadBtn.addEventListener("click", function () { const savedContent = localStorage.getItem("userInput"); if (savedContent) { userInput.innerHTML = savedContent; } });
完整修正后的JavaScript代码
var boldBtn = document.querySelector(".bold"); var italicBtn = document.querySelector(".italic"); var underlineBtn = document.querySelector(".underline"); var colorPicker = document.querySelector(".color-picker"); var highlightBtn = document.querySelector("#highlight"); var bulletPointBtn = document.querySelector("#bulletPoint"); var fontSize = document.querySelector("#fontSize"); var fontInput = document.querySelector("#fontInput"); var fontList = document.querySelector("#fontList"); var saveBtn = document.querySelector("#save"); var userInput = document.querySelector(".userInput"); var loadBtn = document.querySelector("#load"); boldBtn.addEventListener("click", function () { boldBtn.classList.toggle("inUse"); }); italicBtn.addEventListener("click", function () { italicBtn.classList.toggle("inUse"); }); underlineBtn.addEventListener("click", function () { underlineBtn.classList.toggle("inUse"); }); highlightBtn.addEventListener("click", function () { highlightBtn.classList.toggle("inUse"); }); const changeColorText = (color) => { document.execCommand("styleWithCSS", false, true); document.execCommand("foreColor", false, color); }; document.getElementById("highlight").addEventListener("click", function () { var range = window.getSelection().getRangeAt(0), span = document.createElement("span"); span.className = "highlight"; span.appendChild(range.extractContents()); range.insertNode(span); }); bulletPointBtn.addEventListener("click", function () { document.execCommand("insertHTML", false, "<ul><li> </li></ul>"); }); function changeFont() { document.execCommand("fontSize", false, "7"); var fontElements = document.getElementsByTagName("font"); for (var i = 0, len = fontElements.length; i < len; ++i) { if (fontElements[i].size == "7") { fontElements[i].removeAttribute("size"); fontElements[i].style.fontSize = fontInput.value + "px"; } } } fontList.addEventListener("change", function () { document.execCommand("fontName", false, fontList.value); }); // 修正后的保存逻辑 saveBtn.addEventListener("click", function () { localStorage.setItem("userInput", userInput.innerHTML); console.log(localStorage.getItem("userInput")); }); // 修正后的加载逻辑 loadBtn.addEventListener("click", function () { const savedContent = localStorage.getItem("userInput"); if (savedContent) { userInput.innerHTML = savedContent; } });
说明
- 使用
.innerHTML可以完整保存富文本格式(如加粗、斜体、文字颜色等样式),如果只需要纯文本内容,可替换为.textContent localStorage仅支持存储字符串,.innerHTML返回的HTML字符串可直接存入
内容的提问来源于stack exchange,提问作者user18353868
相关产品推荐
相关产品推荐

