拖放生成器如何保存当前选定的小部件/组件状态?

时间:2018-10-19 16:01:18

标签: javascript events drag-and-drop

我知道这可能是一个菜鸟问题。例如,假设一个电子邮件模板构建器。拖放时,在构建器区域说一个图像小部件,然后单击该图像,然后显示一些设置以自定义所选图像。

我的问题是,所选图像的ID /参考存储在哪里,以便所做的任何设置都适用于该图像?

1 个答案:

答案 0 :(得分:0)

由于这样做非常容易,因此我制作了一个超级快速的模型,其中有一个最小的可行示例,可以直接从此处复制:https://developer.mozilla.org/en-US/docs/Web/Events/drop

然后我将其修改为img而不是div,并放入控制台日志中以显示img属性,包括id和它具有的其他任何内容。

var dragged;

/* events fired on the draggable target */
document.addEventListener("drag", function(event) {

}, false);

document.addEventListener("dragstart", function(event) {
  // store a ref. on the dragged elem
  dragged = event.target;
  // make it half transparent
  event.target.style.opacity = .5;
}, false);

document.addEventListener("dragend", function(event) {
  // reset the transparency
  event.target.style.opacity = "";
}, false);

/* events fired on the drop targets */
document.addEventListener("dragover", function(event) {
  // prevent default to allow drop
  event.preventDefault();
}, false);

document.addEventListener("dragenter", function(event) {
  // highlight potential drop target when the draggable element enters it
  if (event.target.className == "dropzone") {
    event.target.style.background = "purple";
  }

}, false);

document.addEventListener("dragleave", function(event) {
  // reset background of potential drop target when the draggable element leaves it
  if (event.target.className == "dropzone") {
    event.target.style.background = "";
  }

}, false);

document.addEventListener("drop", function(event) {
console.log(dragged);
  // prevent default action (open as link for some elements)
  event.preventDefault();
  // move dragged elem to the selected drop target
  if (event.target.className == "dropzone") {
    event.target.style.background = "";
    dragged.parentNode.removeChild(dragged);
    event.target.appendChild(dragged);
  }

}, false);
#draggable {
  width: 200px;
  height: 20px;
  text-align: center;
  background: white;
}

.dropzone {
  width: 200px;
  height: 20px;
  background: blueviolet;
  margin-bottom: 10px;
  padding: 10px;
}
<div class="dropzone">
  <img id="draggable" draggable="true" ondragstart="event.dataTransfer.setData('text/plain',null)" alt="draggableimg" />

</div>
<div class="dropzone"></div>
<div class="dropzone"></div>
<div class="dropzone"></div>