首页 > 解决方案 > 如何修改 YT 视频代码以使其适用于多个对象?

问题描述

我有来自 YT 视频的这段代码,但它只适用于一个对象。我希望它可以处理由 id 名称获取的多个对象。

我试图让这个 'const 填充' 就像它是用 'const empty of emptyies' 制作的,但它没有用

<div class="empty">
    <div class="fill" draggable="true"> </div>
  </div>

  <div class="empty"> 
  </div>

  <div class="empty">
  </div>

<script>

const fill = document.querySelector('.fill');
const empties = document.querySelectorAll('.empty');

// Fill listeners
fill.addEventListener('dragstart', dragStart);
fill.addEventListener('dragend', dragEnd);

// Loop through empty boxes and add listeners
for (const empty of empties) {
  empty.addEventListener('dragover', dragOver);
  empty.addEventListener('dragenter', dragEnter);
  empty.addEventListener('dragleave', dragLeave);
  empty.addEventListener('drop', dragDrop);
}

// Drag Functions

function dragStart(e) {
  this.className += ' hold';
  e.dataTransfer.setData('text', '');
  setTimeout(() => (this.className = 'invisible'), 0);
}

function dragEnd() {
  this.className = 'fill';
}

function dragOver(e) {
  e.preventDefault();
}

function dragEnter(e) {
  e.preventDefault();
  this.className += ' hovered';
}

function dragLeave() {
  this.className = 'empty';
}

function dragDrop() {
  this.className = 'empty';
  this.append(fill);
}

</script>

我希望它适用于我可以拖放的多个对象。

标签: javascript

解决方案


看起来你真的很亲近!我假设您一次只能拖动元素,因此您需要将当前拖动的元素存储在函数可用的某个变量中。我在您尝试编辑的每一行之后添加了评论。

let dragging;  // A place to store the dragging element
const fills = document.querySelectorAll('.fill');
const empties = document.querySelectorAll('.empty');

// Fill listeners
for (const fill of fills) {
fill.addEventListener('dragstart', dragStart);
fill.addEventListener('dragend', dragEnd);
}

// Loop through empty boxes and add listeners
for (const empty of empties) {
  empty.addEventListener('dragover', dragOver);
  empty.addEventListener('dragenter', dragEnter);
  empty.addEventListener('dragleave', dragLeave);
  empty.addEventListener('drop', dragDrop);
}

// Drag Functions
function dragStart(e) {
  dragging = this;
  this.className += ' hold';
  e.dataTransfer.setData('text', '');
  setTimeout(() => (this.className = 'invisible'), 0);
}

function dragEnd() {
  this.className = 'fill';
}

function dragOver(e) {
  e.preventDefault();
}

function dragEnter(e) {
  e.preventDefault();
  this.className += ' hovered';
}

function dragLeave() {
  this.className = 'empty';
}

function dragDrop() {
  this.className = 'empty';
  this.append(dragging);  // Use the element
  dragging = undefined;  // Reset the variable
}
.empty {
  border: 1px solid black;
  min-height: 1em;
}

.fill {
  min-height: 1em;
}

#a.fill {
  background-color: red;
}

#b.fill {
  background-color: blue;
}
<div class="empty">
    <div class="fill" draggable="true" id='a'> </div>
</div>

<div class="empty"> 
    <div class="fill" draggable="true" id='b'> </div>
</div>

<div class="empty">
</div>


推荐阅读