首页 > 解决方案 > 是否可以将整个元素存储到本地存储中?

问题描述

我知道我问的是最愚蠢的,但由于我不熟悉而且我完全是 localstorage 的初学者,我想看看代码的机制是如何工作的,因为它应该是其他的。我创建了一个 div 框和两个按钮,我希望能够更改该框的颜色并将其存储在本地存储中,以便在刷新后我希望以我的样式表的背景颜色结束,即红色。因此,当我在刷新页面以保持该颜色后更改为蓝色时。就像我很伤心,我对本地存储及其使用非常陌生。无论如何,感谢您给我的帮助,我知道这又是一个愚蠢的问题,但我对此非常感兴趣。如您所见,我的javascript代码如下:

var red=document.getElementById("red");
var blue=document.getElementById("blue");


var redColor='red';
var blueColor='blue';

localStorage.setItem('RColor',redColor);
localStorage.setItem('BColor',blueColor);


red.onclick=function red(){
   document.getElementById("box").style.backgroundColor=localStorage.getItem('RColor');


};
blue.onclick=function blue(){
    document.getElementById("box").style.backgroundColor=localStorage.getItem('BColor');


} ;

标签: javascriptlocal-storage

解决方案


检查我下面的评论。这是一个示例用法。

var redColor = 'red';
var blueColor = 'blue';

// When opening, read the Color value from localStorage. If it not set, then use the default color (say red)
document.getElementById("box").style.backgroundColor = localStorage.getItem('Color') || redColor;

var red = document.getElementById("red");
var blue = document.getElementById("blue");

red.onclick = function red() {
    // Once user click on red button, Change the box background and update localStorage with Color
    localStorage.setItem('Color', redColor);
    document.getElementById("box").style.backgroundColor = redColor;
};

blue.onclick = function blue() {
  // Once user click on blue button, Change the box background and update localStorage with Color
  localStorage.setItem('Color', blueColor);
  document.getElementById("box").style.backgroundColor = blueColor;
};

推荐阅读