简体   繁体   English

页面刷新后如何使拖放保持在放置的位置

[英]How to make drag drop stay at dropped place after page refresh

Can someone please help me!有人可以帮帮我吗!

I am working on assignment with drag & drop and localstorage.我正在处理拖放和本地存储的任务。 This is my first time writing a code involving localstorage.这是我第一次编写涉及本地存储的代码。 I'm creating someting like kanban board.我正在创建类似看板的东西。

The problem I am having right now is, I have no idea how am i going to make all cards in the board stay at where i drop it after page refresh.我现在遇到的问题是,我不知道如何让板上的所有卡片在页面刷新后留在我放置的位置。

Here is what i've tried so far这是我到目前为止尝试过的

 const todos = document.querySelectorAll(".todo"); const all_status = document.querySelectorAll(".box") todos.forEach((todo) => { todo.addEventListener("dragstart", dragStart); todo.addEventListener("dragend", dragEnd); }); function dragStart() { draggableTodo = this; setTimeout(() => { this.style.display = "none"; }, 0); console.log("dragStart"); } function dragEnd() { draggableTodo = null; setTimeout(() => { this.style.display = "block"; }, 0); console.log("dragEnd"); } all_status.forEach((box) => { box.addEventListener("dragover", dragOver); box.addEventListener("dragenter", dragEnter); box.addEventListener("draleave", dragLeave); box.addEventListener("drop", dragDrop); }); function dragOver(e) { e.preventDefault(); //console.log("dragOver"); } function dragEnter() { console.log("dragEnter"); } function dragLeave() { console.log("dragLeave"); } function dragDrop() { this.appendChild(draggableTodo); var left = this.offsetLeft; var top = this.offsetTop; localStorage.setItem("left", left); localStorage.setItem("top", top); console.log("dropped"); }

Can check on my JSFiddle too也可以查看我的 JSFiddle

JSFiddle JSFiddle

If there is only one element which you want to keep it's state, "left" and "top" is fine, but you would try to generate a key which defines the element.如果您只想保留一个元素 state,“left”和“top”就可以了,但您会尝试生成一个定义该元素的键。

localStorage.setItem("elementAPosition", {left: '10px', top: '5px'})

And when your scripts run at the first place, you can check element positions and set their place.当您的脚本首先运行时,您可以检查元素位置并设置它们的位置。

let elementAPos = localStorage.getItem("elementAPosition") //this returns an object with left and top keys.
elementA.style.left = elementAPos.left
elementA.style.top = elementAPos.top

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM