繁体   English   中英

如何将背景色保存到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 = "red";

  return false;
}

如果要与项目一起存储背景色,则需要将项目作为对象而不是名称存储。

我建议将这样的逻辑添加到您的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;
}

然后,当您显示()那些,您的循环将如下所示:

  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>";
  };

然后,当您设置对象的优先级时,您只需设置

todos[i].priority.isPriority = true;

todos[i].priority.color = "red";

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

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

看看这个例子: https : //jsfiddle.net/1Lgrb7c8/2/

暂无
暂无

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

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