-
-
Save nora-tetsu/51a587d0045f79d6ad2ee59b3fbdbdb8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const storageKey = 'hoge'; // localStorageに保存する際のキーが「hoge」だとする | |
const list = document.getElementById('list'); // 「list」というidを付けたul要素があるとする | |
function loadData() { | |
const json = localStorage.getItem(storageKey); // localStorageからデータを取り出す(文字列) | |
const data = JSON.parse(json); // 文字列からデータに復元する | |
/* | |
データの中身は以下のような形式のオブジェクトの配列だとする | |
{ | |
text: '本日は晴天なり', | |
top: '50px', | |
left: '100px', | |
} | |
*/ | |
data.forEach(item => { // データそれぞれについて | |
const elm = list.appendChild(document.createElement('li')); // ul要素の子要素としてli要素を追加する | |
elm.classList.add('fusen'); // 「fusen」クラスを付けておく | |
elm.textContent = item.text; // 本文をセット | |
elm.style.top = item.top; // topの値(=縦位置)をセット | |
elm.style.left = item.left; // leftの値(=横位置)をセット | |
}) | |
} | |
function saveData() { | |
const elms = list.getElementsByClassName('fusen'); // ul要素内の全てのli要素を取得する | |
const data = []; // データを入れる配列を作っておく | |
Array.from(elms).forEach(elm => { // li要素それぞれについて | |
const item = { // データのオブジェクトを作る | |
text: elm.textContent, | |
top: elm.style.top, | |
left: elm.style.left, | |
} | |
data.push(item); // 配列にデータを入れる | |
}) | |
localStorage.setItem(storageKey, JSON.stringify(data)); // localStorageに保存する | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment