gpt4 book ai didi

javascript - 本地存储-Jquery

转载 作者:行者123 更新时间:2023-11-27 23:41:48 24 4
gpt4 key购买 nike

问题是,当我单击按钮时,它会创建一个可拖动的 div 克隆,并且我想在刷新后使用本地存储保存克隆移动的 div 的位置。现在使用我的代码我可以保存原始div,但克隆的div在刷新后被删除。请提供解决方案以获得所需的功能。对于JS:

var sPositions = localStorage.positions || "{}",
positions = JSON.parse(sPositions);
$.each(positions, function (id, pos) {
$("#" + id).css(pos)
})
$("#divd").draggable({
containment: "#containment-wrapper",
scroll: false,
stop: function (event, ui) {
positions[this.id] = ui.position;
localStorage.positions = JSON.stringify(positions);
}
});


$("#button").click(function () {
$("#divd").clone().insertAfter("#body").draggable();
});

这是原始的 div 代码 -

<div id="divd" class="draggable ui-widget-content"></div>
<button id="button">Button</button>

最佳答案

加载时重新创建所有div,并将它们与draggable绑定(bind)。

请参阅下面的示例:

var globalCount = 1;
var sPositions = localStorage.positions || "{}",
positions = JSON.parse(sPositions);
$.each(positions, function (id, pos) {
if(id != "divd"){
var cloned = $("#divd").clone();
cloned[0].id = id;
cloned.insertAfter("#divd")
globalCount++;
}
$("#" + id).css(pos)
});
$(".common-drag").draggable({
containment: "#containment-wrapper",
scroll: false,
stop: function (event, ui) {
positions[this.id] = ui.position
localStorage.positions = JSON.stringify(positions)
}
});

$("#button").click(function () {
var cloned = $("#divd").clone();
cloned[0].id = "divd" + globalCount++;
cloned.insertAfter("#divd").draggable({
containment: "#containment-wrapper",
scroll: false,
stop: function (event, ui) {
positions[this.id] = ui.position
localStorage.positions = JSON.stringify(positions)
}
});
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css">

<div id="divd" class="draggable ui-widget-content common-drag">Test</div>
<button id="button">Button</button>

演示:http://jsfiddle.net/kishoresahas/sh72djwz/

具有多种类型的 Div:

演示:http://jsfiddle.net/kishoresahas/sh72djwz/2/

关于javascript - 本地存储-Jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33596865/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com