简体   繁体   English

如何将背景色保存到localStorage?

[英]How do I save background color to localStorage?

I have a to-do list that saves to localStorage with a Priority button that changes the background color to red. 我有一个待办事项列表,可通过“优先级”按钮将背景颜色更改为红色来保存到localStorage。 That color doesn't save on refresh or adding a new to-do item. 该颜色不会保存在刷新或添加新的待办事项上。 Is it possible to save color to localStorage? 是否可以将颜色保存到localStorage? https://jsfiddle.net/kiddigit/hg6w01zn/ 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: 我建议将这样的逻辑添加到您的add方法中:

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: 如果要基于属性定义颜色,则可以在html中将属性设置为isPriority = true,然后在CSS中执行以下操作:

[isPriority="true"] {
    background-color: red;
}

Check out this example: https://jsfiddle.net/1Lgrb7c8/2/ 看看这个例子: https : //jsfiddle.net/1Lgrb7c8/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM