所以我设置了Jquery draggable,以便用户可以更改父div中div的位置。
执行第一次删除时,所有位置都保存到localstorage。每次进行放下时,都会更新此数据。
刷新页面时,div位置将根据localstorage中保存的位置正确显示。当我然后单击一个div来开始拖放过程时,周围的div不会按预期移动或者在页面刷新之前它们如何移动。
HTML
<div id="sortable">
<div id="test0" style="background-color: yellow; border: solid 1px black; height: 50px; width: 100px;">
<div class='ui-state-default'>Test0</div>
</div>
<div id="test1" style="background-color: yellow; border: solid 1px black; height: 50px; width: 100px;">
<div class='ui-state-default'>Test1</div>
</div>
<div id="test2" style="background-color: yellow; border: solid 1px black; height: 50px; width: 100px;">
<div class='ui-state-default'>Test2</div>
</div>
<div id="test3" style="background-color: yellow; border: solid 1px black; height: 50px; width: 100px;">
<div class='ui-state-default'>Test3</div>
</div>
<div id="test4" style="background-color: yellow; border: solid 1px black; height: 50px; width: 100px;">
<div class='ui-state-default'>Test4</div>
</div>
<button onclick="localStorage.clear();">Clear Local Storage</button>
的Javascript
$( function() {
newPosVal = [];
if (localStorage.getItem("newData") != null){
var storedData = JSON.parse(localStorage.getItem("newData"));
console.log("New position Local Storage data being used:");
console.log(storedData);
for (var i = 0; i < storedData.length; i++) {
console.log("stored: #test" + storedData[i]['div_id'] + " " + storedData[i]['offset_top_position']);
var id = storedData[i]['div_id'];
var position = storedData[i]['offset_top_position'];
$('#test' + id).offset({top:position});
console.log("Pos Check: #test" + id, $("#test" + id).offset().top);
}
}
$( '#sortable' ).sortable({
revert: false,
stop: function() {
if (localStorage.getItem("newData") != null){
var dataNew = jQuery.parseJSON(localStorage.getItem("newData"));
console.log("New position Local Storage data being used:");
console.log(dataNew);
for (var i = 0; i < dataNew.length; i++) {
console.log("previous: #test" + dataNew[i]['div_id'] + " " + dataNew[i]['offset_top_position']);
id = dataNew[i]['div_id'];
position = dataNew[i]['offset_top_position'];
offset = $('#test' + id).offset();
newPosVal[i] = {"div_id":id, "offset_top_position":offset.top};
console.log("Newly stored: #test" + id, $("#test" + id).offset().top);
}
console.log("New Position Using Local Storage data: " + JSON.stringify(newPosVal));
localStorage.setItem("newData", JSON.stringify(newPosVal));
} else {
console.log("No div position data is being used");
for(var i=0; i < 5; i++) {
var id = i;
var offset = $('#test' + id).offset();
newPosVal[i] = {"div_id":id, "offset_top_position":offset.top};
}
console.log("First Position Data: " + JSON.stringify(newPosVal));
localStorage.setItem("newData", JSON.stringify(newPosVal));
}
}
});
$( '#draggable' ).draggable({
connectToSortable: '#sortable',
//helper: 'clone',
revert: false
});
});