使用本地存储在javascript中保存图像

时间:2018-06-09 14:36:44

标签: javascript local-storage

检查我的JS小提琴:https://jsfiddle.net/oxfre6kj/1/

我有一个按钮可以创建任意数量的图像,但是当我刷新页面时这些图像消失了,我希望它们在单击保存按钮后仍然存在。

以下是我尝试使用变量但它不适​​用于“img”

<button onclick="createImage()">Create Image</button>
<button onclick="saveImages()">Save Images</button>
<div id="image"></div>

<script>
function createImage() {
        var img = document.createElement('img');
        img.src = 'http://via.placeholder.com/350x150';       
        document.getElementById('image').appendChild(img);
}


var image = localStorage.getItem('image');
alert(image);

function saveImage() {
    localStorage.setItem("images", image);
}
</script>

1 个答案:

答案 0 :(得分:1)

这是你希望页面如何工作的?

HTML:

&#13;
&#13;
<button id="create_image">Create Image</button>
<button onclick="saveImages()">Save Images</button>

<label for="image_url">Image url :</label>
<input type="text" id="image_url" value="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded" placeholder="img url">

<div id="images"></div>
&#13;
&#13;
&#13;

JAVASCRIPT:

&#13;
&#13;
document.getElementById("create_image").addEventListener("click", function() {
  const url = document.getElementById("image_url").value;
  createImage(url);
});

var images = localStorage.getItem('image');
loadImagesFromLocal();

function createImage(src) {
  var img = document.createElement('img');
  img.src = src;
  img.onload = function() {
    document.getElementById('images').appendChild(img);
  }
}

function saveImages(img) {
  const images = document.querySelectorAll(`div#images img`);
  var savedImagesSrc = JSON.parse(localStorage.getItem("images")) || [];
  savedImagesSrc = Array.from(savedImagesSrc);

  for (var i = savedImagesSrc.length; i < images.length; i++) {
    savedImagesSrc.push(images[i].src);
  }

  localStorage.setItem("images", JSON.stringify(savedImagesSrc));
}

function loadImagesFromLocal() {
  const savedImagesSrc = JSON.parse(localStorage.getItem("images")) || [];

  for (var i = 0; i < savedImagesSrc.length; i++) {
    createImage(savedImagesSrc[i]);
  }

}
&#13;
&#13;
&#13;