HTML/CSS可拖动元素

rhfm7lfc  于 2023-06-07  发布在  其他
关注(0)|答案(1)|浏览(150)

你好。我正在尝试用非常简单的基于HTML/CSS的可拖动树表示来构建一个应用程序。

<div class="tree">
  <div class="leaf" draggable=true>
    <div class="leaf-handle">item 1</div>
    <div class="leaf subleaf" draggable=true>
      <div class="leaf-handle">item 1.1</div>
      <div class="leaf subsubleaf" draggable=true>
        <div class="leaf-handle">item 1.1.1</div>
      </div>
    </div>
  </div>
  <div class="leaf" draggable=true>
    <div class="leaf-handle">item 2</div>
    <div class="leaf subleaf" draggable=true>
      <div class="leaf-handle">item 2.1</div>
      <div class="leaf subsubleaf" draggable=true>
        <div class="leaf-handle">item 2.1.1</div>
      </div>
    </div>
  </div>
</div>

再现案例的代码示例可以在这里找到:https://codepen.io/DerZinger/pen/bGQbEmd
我面临的问题是,当我试图拖动一个分支(带有子项的项)时,“幽灵”图像(可拖动元素的表示)有不透明的背景,无论我尝试什么,我都无法删除。
像这样:

我真的需要它是不可见的(重影图像只显示分支的叶手柄,这是当前拖动)。
任何关于如何实现这一点的帮助或指导将非常感谢。
编辑1:有人建议删除背景色。我试过了,可惜没用,这就是重点。删除它,设置它不透明,以及其他任何-所有这些技巧最终都不会“隐藏”我想隐藏的区域:

46qrfjad

46qrfjad1#

在对你的问题测试了几个变通方法并做了在线研究之后,我终于想出了一个不错的解决方案;不是完美的一个但今天最好的。

编码:

document.addEventListener("dragstart", function (event) {
  document.querySelector(".tree").style.backgroundColor = "transparent";
  event.target.style.background = "transparent";
  setTimeout(() => {
    document.querySelector(".tree").style.backgroundColor = "red";
    event.target.style.background = "yellow";
  }, 100);
});
.leaf {
  background-color: yellow;
  width: 200px;
}
.leaf-handle {
  background-color: green;
  border: 1px solid black;
}
.tree {
  background-color: red;
  display: flex;
  flex-direction: column;
}

.subleaf {
  padding-left: 30px;
}
.subsubleaf {
  margin-left: 60px;
}
<div class="tree">
  <div class="leaf" draggable="true">
    <div class="leaf-handle">item 1</div>
    <div class="subleaf">
      <div class="leaf-handle">item 1.1</div>
      <div class="subsubleaf">
        <div class="leaf-handle">item 1.1.1</div>
      </div>
    </div>
  </div>
  <div class="leaf" draggable="true">
    <div class="leaf-handle">item 2</div>
    <div class="leaf subleaf" draggable="true">
      <div class="leaf-handle">item 2.1</div>
      <div class="leaf subsubleaf" draggable="true">
        <div class="leaf-handle">item 2.1.1</div>
      </div>
    </div>
  </div>
</div>
<div class="tree">
  <div class="leaf" draggable="true">
    <div class="leaf-handle">item 1</div>
    <div class="leaf subleaf" draggable="true">
      <div class="leaf-handle">item 1.1</div>
      <div class="leaf subsubleaf" draggable="true">
        <div class="leaf-handle">item 1.1.1</div>
      </div>
    </div>
  </div>
  <div class="leaf" draggable="true">
    <div class="leaf-handle">item 2</div>
    <div class="leaf subleaf" draggable="true">
      <div class="leaf-handle">item 2.1</div>
      <div class="leaf subsubleaf" draggable="true">
        <div class="leaf-handle">item 2.1.1</div>
      </div>
    </div>
  </div>
</div>

相关问题