javascript - 是否可以将整个元素存储到本地存储中?
问题描述
我知道我问的是最愚蠢的,但由于我不熟悉而且我完全是 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');
} ;
解决方案
检查我下面的评论。这是一个示例用法。
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;
};
推荐阅读
- ruby-on-rails - Rails 应用程序中的 CanCanCan gem:对特定关系条件的错误解释和意外弃用警告
- android - 如何从本地存储加载媒体以将视频投射到 Android TV?
- java - 将 JHipster 项目部署到 tomcat 服务器
- r - 如何基于另一个矩阵创建一个矩阵
- python - Python com 文件用 pyinstaller 打包成 exe 后如何注册?
- swiftui - SwiftUI - TabView 禁用背景透明度
- .net-core - 如何停止并行执行被 backgroundhangfire 作业多次排队的方法
- spring-boot - 春季启动中的 HMAC TOEKN 安全性
- reactjs - React Native:将内联样式道具传递给组件时出现错误“类型'IntrinsicAttributes&...”上不存在属性'样式'
- android - 应用程序重新启动时初始化不起作用