我正在努力学习如何使用localStorage。
在一定程度上模仿,我编写了html,它生成了一个带有几个平铺的页面,您可以在页面上拖放这些平铺。
例如
<script type="text/javascript">
function drag_start(event){
var style = window.getComputedStyle(event.target, null);
var str = (parseInt(style.getPropertyValue("left")) - event.clientX) + ',' + (parseInt(style.getPropertyValue("top")) - event.clientY)+ ',' + event.target.id;
event.dataTransfer.setData("Text",str);
event.stopPropagation();
}
function drop(event){
var offset = event.dataTransfer.getData("Text").split(',');
var dm = document.getElementById(offset[2]);
dm.style.left = (event.clientX + parseInt(offset[0],10)) + 'px';
dm.style.top = (event.clientY + parseInt(offset[1],10)) + 'px';
localStorage.setItem(dm.id,dm.style.left);
event.preventDefault();
return false;
}
function drag_over(event){
event.preventDefault();
return false;
}
</script>
我认为,用上面以"localStorage"开头的一行,我可以将放置后的位置保存在localStorage
中。[当前行只是一个模拟示例。稍后,当我了解这些内容时,我会实际存储位置或偏移量。]
我感到困惑的部分是如何在加载页面时从localStorage
检索位置。
比方说,我将有一块瓷砖是
<div id="tile3" draggable="true" ondragstart="drag_start(event)">
<a href="http://www.link.somewhere">
Link
</a>
</div>
我可以说瓦片具有style="position:absolute"
,然后我需要从localStorage
检索偏移并设置为div
的属性。
但是如何完成最后一部分呢?
对于保存,您使用以下javascript命令:
(假设位置是一个有两个值(x和y位置(的数组(
localStorage.setItem("position", JSON.Stringify(thePosition));
在页面加载上,你可以做这样的事情(假设你使用jquery(:
$(document).ready(function(){
var position = JSON.parse(localStorage.getItem("position"));
$('#the-divs-id').css({'left': position[0], 'top': position[1]});
});
edit:为数组添加了JSON字符串/解析
如果你不想使用jquery:
window.onload = setDiv();
function setDiv(){
var position = JSON.parse(localStorage.getItem("position"));
document.getElementById(the-divs-id).style.left = position[0];
document.getElementById(the-divs-id).style.top = position[1];
}
编辑:循环问题:
$(document).ready(function(){
// loops trough all divs with the-class
$('.the-class').each(function(){
// get the id from the current div
// and get the corresponding position from local storage
var id = $(this).attr('id'),
position = JSON.parse(localStorage.getItem(id));
// sets the css values for the current div
$(this).css({'left': position[0], 'top': position[1]});
});
});