如何将颜色框保存到本地存储中?

时间:2018-09-06 03:12:15

标签: javascript dom ecmascript-6 javascript-events local-storage

我想在提交时将这些颜色div框保存到本地存储中(输入值将作为backgroundColor添加到div框中) 预先感谢!

apples
carrots
lewis
const
  container = document.querySelector('.save-boxes .container'),
  myForm = document.getElementById('myForm');
myForm.addEventListener('submit', addBox);

// Adding div element
function addBox(e) {
    e.preventDefault();
    let inputVal = input.value; // value
    if(!inputVal) return;  

    let box = document.createElement('div');
    box.className = 'hex-bg';
    box.style.backgroundColor = input.value;

    // hex-text
    let hexText = document.createElement('div');
    hexText.classList.add('hex-text');
    hexText.textContent = input.value;

    box.appendChild(hexText); // append input text on div   

    container.appendChild(box); // apppend 'hex-bg' div
    box.addEventListener('click', remove);

    this.reset();
}

// removing element on click
function remove() {
    let parent = this.parentElement;
    parent.removeChild(this); 
}
.container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
.hex-bg {
  align-items: center;
  border: 1px solid #ccc;
  display: flex;
  height: 200px;
  justify-content: center;
  width: 200px;
}

其工作方式示例:

Here is an example of result

1 个答案:

答案 0 :(得分:0)


您可以将背景色十六进制代码保存在本地存储中,并在重新访问时可以阅读本地存储并重新绘制div框。
有关本地存储click here

的更多信息