我想将拖动保存到localStorage,但是当我刷新时,拖动的位置不是放置它的位置。我使用了jQuery UI | Draggable。

JSFIDDLE.

我们如何将其保存到localStorage?

的HTML

<p id="text">Lorem ipsum dolor sit amet.</p>
<button id="save">Save localStorage</button>
<button id="clear">Clear localStorage</button>

<div id="append-area"></div>


JS

$(function() {

$("#save").click(function() {
var text =$("#text").text();
$("#append-area").append(text+"<br>");

var appended=$("#append-area").html();
localStorage.setItem("appended",appended);
});

if (localStorage.getItem('appended')) {
  $('#append-area').html(localStorage.getItem('appended'));
}

$("#append-area").draggable();

$("#clear").click(function() {
 window.localStorage.clear();
 window.location.reload();
});

});

最佳答案

试试这个,希望这就是您正在寻找的.. :)

小提琴链接https://jsfiddle.net/5mwndskb/1/

 $(function() {
  var getPos = JSON.parse(localStorage.getItem("appended"));
  var currentPos = {
    top: 0,
    left: 0
  };
  if (getPos !== null && getPos.top !== null) {
    $('#append-area').css({
      top: getPos.top,
      left: getPos.left
   }).append(getPos.txt);
  };

  $('#append-area').draggable({

    drag: function(event, ui) {

      currentPos = $(this).position();
    }
  });

  $("#save").click(function() {
    var text = $("#text").text();
    currentPos.txt = text;
    $("#append-area").append(text + "<br>");
    localStorage.setItem("appended", JSON.stringify(currentPos));
  });

  $("#clear").click(function() {
    window.localStorage.clear();
    window.location.reload();
  });

});

关于jquery - 如何将拖放保存到localStorage?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36384414/

10-09 01:48