beg*_*123 7 html javascript css html5
我正在尝试学习如何使用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>
Run Code Online (Sandbox Code Playgroud)
我认为,如上所述,以"localStorage"开头,我可以保存 localStorage
下降后该位置.[目前的线条只是一个模拟的例子.后来,当我理解这些东西时,我会实际存储位置或偏移.]
我感到困惑的部分是关于如何从localStorage
页面加载时检索位置.
说,我将有一块瓷砖
<div id="tile3" draggable="true" ondragstart="drag_start(event)">
<a href="http://www.link.somewhere">
Link
</a>
</div>
Run Code Online (Sandbox Code Playgroud)
我可以说瓷砖有style="position:absolute"
,然后我需要从中检索偏移localStorage
并设置为该属性div
.
但是如何做最后一部分呢?
(假设 thePosition 是一个具有两个值(x 和 y 位置)的数组)
localStorage.setItem("position", JSON.Stringify(thePosition));
Run Code Online (Sandbox Code Playgroud)
在页面加载上你可以做这样的事情(假设你使用jquery):
$(document).ready(function(){
var position = JSON.parse(localStorage.getItem("position"));
$('#the-divs-id').css({'left': position[0], 'top': position[1]});
});
Run Code Online (Sandbox Code Playgroud)
编辑:为数组添加 JSON stringify/parse
如果你不想使用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];
}
Run Code Online (Sandbox Code Playgroud)
编辑:循环问题:
$(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]});
});
});
Run Code Online (Sandbox Code Playgroud)