javascript - 如何在本地存储中保存图像位置
问题描述
我有一个问题,目前我正在尝试将图像位置保存在本地存储中,但我不知道该怎么做。我希望它在本地存储中,因为一旦您刷新页面,我仍然想要您拖动的图像,与您在页面刷新/重新加载之前将图像拖动到的位置相同。该脚本就像一个包含图像项目的库存。
这是代码:
const fill1 = document.querySelector('#item1');
const empties1 = document.querySelectorAll('#block1');
const empties2 = document.querySelectorAll('#block2');
const spot1 = document.getElementById("block1")
const spot2 = document.getElementById("block2")
checkSpot1()
checkSpot2()
localStorage.spot1 = 1
localStorage.spot2 = 0
// Fill listeners
fill1.addEventListener('dragstart', dragStart);
fill1.addEventListener('dragend', dragEnd);
// Loop through empty boxes and add listeners
for (const empty of empties1) {
empty.addEventListener('dragover', dragOver);
empty.addEventListener('dragenter', dragEnter);
empty.addEventListener('dragleave', dragLeave);
empty.addEventListener('drop', dragDrop);
}
for (const empty of empties2) {
empty.addEventListener('dragover', dragOver);
empty.addEventListener('dragenter', dragEnter);
empty.addEventListener('dragleave', dragLeave);
empty.addEventListener('drop', dragDrop);
}
// Drag Functions
function dragStart() {
this.idName += ' hold';
setTimeout(() => (this.idName = 'invisible'), 0);
}
function dragEnd() {
this.idName = 'fill1';
}
function dragOver(e) {
e.preventDefault();
}
function dragEnter(e) {
e.preventDefault();
this.idName += ' hovered';
}
function dragLeave() {
this.idName = 'empties1';
this.idName = 'empties2';
}
function dragDrop() {
this.idName = 'empties1';
this.idName = 'empties2';
this.append(fill1);;
}
function checkSpot1() {
if (localStorage.getItem("spot1") == 1) {
}
}
function checkSpot2() {
if (localStorage.getItem("spot2") == 1) {
}
}
spot1.addEventListener('dragend', setspot1)
spot2.addEventListener('dragend', setspot2)
function setspot1(){
localStorage.spot1 = 1
localStorage.spot2 = 0
}
function setspot2(){
localStorage.spot1 = 0
localStorage.spot2 = 1
}
但是就像我说的那样,我不知道如何正确地将其存储在本地存储中,并使其显示在页面重新加载之前图像被拖到的位置。
解决方案
如果你想保存一些东西到 localStorage,它必须是字符串格式。
所以,如果你想保存第一点,它看起来像:
localStorage.setItem("spot1", "0")
其中“spot1”是键,“0”是值。
从 localStorage 中检索:
localStorage.getItem("spot1")
这应该返回“0”
推荐阅读
- python - 如何在 PyOpenGL 中旋转某个对象(四边形)?
- javascript - How to create a new class instance from within an instance?
- facebook-graph-api - Where to get product-catalog-id
- sql - 如何将特定行值转换为配置单元中的列标题
- javascript - Canvas, how to set line dash of line?
- node.js - 服务| -v | ubuntu 终端中的任何命令都不起作用,而在 intellij 的本地终端中它正在工作
- gitlab - GitLab API get commit count of a branch
- python - 如何将列表列表作为单独的列添加到现有数据框中
- ios - 如何在加号图标上快速添加一些操作
- sql - 为什么这个 INTO 语句没有创建新表?