JavaScript 更改元素颜色并使用 LocalStorage 存储

JavaScript change elements color and store with LocalStorage

我想做一个改变元素颜色的按钮,并用LocalStorage存储改变的颜色。老实说,我是 LocalStorage 的新手,但我已经尽力了。它几乎可以工作,但有点错误,并没有真正保存更改。知道如何使其可行吗?

代码:

function markasRead() {

    var message = document.getElementById("msgContainer");
    var marbtn = document.getElementById("markasread");

    const wasRead = localStorage.getItem('message') === 'true';

    if (!message.classList.contains("readMsg")) {
        marbtn.innerHTML = "Mark as unread";
        localStorage.setItem('message', !wasRead);
        message.classList.toggle("readMsg", !wasRead);
    } else if (message.classList.contains("readMsg")) {
        message.classList.remove("readMsg");
        message.classList.toggle("readMsg", wasRead);
        marbtn.innerHTML = "Mark as read";
    }

}

function onloadread() {
    message.classList.toggle('readMsg', localStorage.getItem('message') === 'true');
}
#msgContainer {
  background-color: red;
}

.readMsg {
    background-color: gray !important;
}
<body onload="onloadread()">
<div id="msgContainer">
Some text...<br>
<button id="markasread" onclick="markasRead()">Mark as read</button>
</div>
</body>

试用这段代码并告诉我,这是否是您想要实现的。

function markasRead() {
  const message = document.getElementById("msgContainer");
  const marbtn = document.getElementById("markasread");
  const wasRead = JSON.parse(localStorage.getItem('message'));
  if (!wasRead || wasRead === false) {
    marbtn.innerHTML = "Mark as unread";
  } else {
    marbtn.innerHTML = "Mark as read";
  }
  localStorage.setItem('message', !wasRead);
  message.classList.toggle("readMsg");
}

function onloadread() {
  const message = document.getElementById("msgContainer");
  const marbtn = document.getElementById("markasread");
  if(JSON.parse(localStorage.getItem('message'))) {
    marbtn.innerHTML = "Mark as unread";
    message.classList.toggle('readMsg');
  }
}