使用sessionstorage保存可拖动的其他图像

时间:2019-01-15 19:15:33

标签: javascript image drag-and-drop storage

我尝试在div中拖动图像,并希望将其保存在sessionstorage中,以便将其放置在另一页的同一位置。

1。。我不知道如何保存拖动图像,因为有许多不同的图像。 2。。我尝试了一些方法,但是没有用

<div  ondrop="drop(event)" ondragover="allowDrop(event)">
<img  src="ayfsdxcfgh.png" draggable="true" ondragstart="drag(event)" id="drag1">
        <img src="aysdx.png" id="drag2" draggable="true" ondragstart="drag(event)" >
    </div>
    <h2>items</h2>
    <div class="items" ondrop="drop(event)" ondragover="allowDrop(event)">  
    </div>

    var inventar = {};

function addItem(key, value) {
    inventar[key] = value;
    window.localStorage.setItem("data", JSON.stringify(inventar));
}


function loadInventar() {
    inventar = JSON.parse(window.localStorage.getItem("data"));
    console.log(inventar);
    for (key in inventar) {
        console.log(key + " - " + inventar[key]); 
        document.getElementById(key).appendChild(document.getElementById(inventar[key]));

          var x = document.createElement("IMG");
          x.setAttribute("src", "pic/Icons/' + inventar[key] + '");
          document.getElementById(key).appendChild(x);

        document.getElementById(key).innerHTML = '<img src="pic/Icons/' + inventar[key] + '" onclick="()">';

    }
    return 123;
}

function inventarReset() {
    window.localStorage.clear();
}

function drop(ev) {
    ev.preventDefault();

    console.log(ev);
    console.log(ev.target.id);

    var data = ev.dataTransfer.getData("img");
    addItem(ev.target.id, data);
    console.log(data);
    ev.target.style.border = "0px dashed transparent";
    if (ev.target=="[object HTMLImageElement]"){ //nur ein objekt in jeden kasten
           ev.target = ev.target.parentNode;
        }
    else { 
        ev.target.appendChild(document.getElementById(data));
    }
}

1 个答案:

答案 0 :(得分:0)

drop()函数中保存img id:

function drag(ev) {
    ev.dataTransfer.setData("img", ev.target.id);
}
function drop(ev){
  var data = ev.dataTransfer.getData("img");
 sessionStorage.setItem("imgData", data);
}