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

问题描述 投票:0回答:1

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

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;
}
<form id="myForm">
    <input id='input' type="text" placeholder="#821ab9" autofocus autocomplete="off" maxlength="7">
    <button>add</button>
   </form>

<!-- color boxes added from javascript -->
<div class="save-boxes">
    <div class="container">

       <!-- the sample div will be added..
        <div class="hex-bg" style="background-color: #fc06cc;">
            <div class="hex-text">#fc06cc</div>
        </div>
        -->

    </div>
</div>

工作实例。

Here is an example of result

javascript dom ecmascript-6 javascript-events local-storage
1个回答
0
投票

您可以将背景色的十六进制代码保存在本地存储中,当您再次访问时,您可以读取本地存储并重新绘制div框。关于本地存储的更多信息 点击这里

© www.soinside.com 2019 - 2024. All rights reserved.