如何将背景色保存到localStorage? [英] How do I save background color to localStorage?
问题描述
我有一个待办事项列表,可通过优先级"按钮将背景颜色更改为红色,将其保存到localStorage.该颜色不会在刷新或添加新的待办事项时节省.是否可以将颜色保存到localStorage? https://jsfiddle.net/kiddigit/hg6w01zn/
function priority(){var id = this.getAttribute('value');var todos = get_todos();localStorage.setItem('todo',JSON.stringify(todos));document.getElementById(id).style.background =红色";返回false;}
如果要为项目存储背景颜色,则需要将项目存储为对象,而不仅仅是名称.
>
我建议将这样的逻辑添加到您的添加方法中:
function add(){var task = document.getElementById('task').value;var todos = get_todos();var newTask = {名称:任务,id:"item" + todos.length,优先事项: {isPriority:false,颜色:""}};todos.push(newTask);localStorage.setItem('todo',JSON.stringify(todos));表演();返回false;}
然后,当您显示()那些时,您的循环将如下所示:
for(var i = 0; i< todos.length; i ++){var todo = todos [i];html + =< p id ='item" + i +'isPriority ='" +todo.priority.isPriority +'>"+ todo ["name"] +'< p>'+< button class ='删除'>删除</button>"+" +<按钮类='优先级'值='项目'+ i +'>优先级</button>";};
然后,当您设置对象的优先级时,您只需设置
todos [i] .priority.isPriority = true;
和
todos [i] .priority.color =红色";
如果要基于属性定义颜色,则可以在html中将属性设置为isPriority = true,然后在CSS中执行以下操作:
[isPriority ="true"] {背景颜色:红色;}
看看这个例子:https://jsfiddle.net/1Lgrb7c8/2/>
I have a to-do list that saves to localStorage with a Priority button that changes the background color to red. That color doesn't save on refresh or adding a new to-do item. Is it possible to save color to localStorage? https://jsfiddle.net/kiddigit/hg6w01zn/
function priority() {
var id = this.getAttribute('value');
var todos = get_todos();
localStorage.setItem('todo', JSON.stringify(todos));
document.getElementById(id).style.background = "red";
return false;
}
If you want to store a background color with the item, you're going to need to store the item as an object instead of just the name.
I recommend adding logic like this to your add method:
function add() {
var task = document.getElementById('task').value;
var todos = get_todos();
var newTask = {
name:task,
id: "item" + todos.length,
priority: {
isPriority:false,
color:""
}
};
todos.push(newTask);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false;
}
Then, when you show() those, your loop will look like this:
for (var i = 0; i < todos.length; i++) {
var todo = todos[i];
html += "<p id='item" + i + "' isPriority='" +
todo.priority.isPriority + "'>" + todo["name"] + '<p>' +
"<button class='remove'>Delete</button>" + " " +
"<button class='priority' value='item" + i + "'>Priority</button>";
};
Then when you set the priority on the object, you're just setting the
todos[i].priority.isPriority = true;
and
todos[i].priority.color = "red";
If you want to define your color based on the property, you could just set a property in the html as isPriority=true and then in css do this:
[isPriority="true"] {
background-color: red;
}
Check out this example: https://jsfiddle.net/1Lgrb7c8/2/
这篇关于如何将背景色保存到localStorage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!