我试图做可拖动的待办事项列表,我遇到了这个问题。 这是HTML:
<div class="to-do-element editing" draggable="true">
<div class="text-wrapper">
<span><span class="index">1</span>.</span>
<span class="to-do-text"></span>
<input type="text" class="to-do-input" placeholder="Click to add text."/>
</div>
<div class="buttons">
<button type="button" class="save-button icon-checkmark" data-button="save"></button>
<button type="button" class="edit-button icon-pencil" data-button="edit"></button>
<button type="button" class="delete-button icon-cross" data-button="delete"></button>
<button type="button" class="move-up-button icon-arrow-up2" data-button="move-up"></span></button>
<button type="button" class="move-down-button icon-arrow-down2" data-button="move-down"></button>
<button type="button" class="cross-out-button icon-strikethrough" data-button="cross-out"></button>
<button type="button" class="uncross-out-button icon-undo" data-button="uncross-out"></button>
</div>
</div>
和JS:
thisDiv.addEventListener('dragover', (e) => {
e.preventDefault();
});
thisDiv.addEventListener('dragstart', (e) => {
console.log(e.target.querySelector('.index').innerText);
e.dataTransfer.setData('text', e.target.querySelector('.index').innerText);;
});
thisDiv.addEventListener('drop', (e) => {
console.log(document.querySelector('.to-do-element:nth-of-type(' + e.dataTransfer.getData('text') + ')'));
console.log(e);
document.querySelector('#to-do-list').insertBefore(document.querySelector('.to-do-element:nth-of-type(' + e.dataTransfer.getData('text') + ')'), e.target);
})
事情是e.target
太具体了,我想知道我指的是哪个,但如果我指的是完全指向跨度,它会让我回到跨度等等。我想过使用像.parentElement
这样的东西,但没有帮助。我可以循环.path
并进行比较,但我正在寻找更好的方法。