【问题标题】:Why is my ondragstart operation being undone immediately after executing?为什么我的 ondragstart 操作在执行后立即被撤消?
【发布时间】:2020-05-28 18:45:04
【问题描述】:
我正在制作一个具有三个分组级别的拖放式表单构建器:部分,其中包含问题,其中包含选项。选项可以在问题内和之间拖动,问题可以在部分内和之间拖动,并且可以相互排序。
我正在使用 Bootstrap 的 collapse/show 类来隐藏大多数问题,因为它们开始被拖动,因为有些问题可以有十几个选项,并且在拖动时保持打开状态不会让您看到任何问题下面的问题。
但是,一旦ondragstart 执行并从问题主体中删除show 类,折叠它,它似乎立即被撤消。
我尝试在调试器中单步执行在 ondragstart 之后调用的每一行,但找不到任何可以重新添加 show Bootstrap 类的内容。
小提琴:https://jsfiddle.net/robertgreenstreet/jrdmvasw/4/
【问题讨论】:
标签:
javascript
html
drag-and-drop
【解决方案1】:
事实证明,我需要的只是为问题添加一个条件到 ondragenter 函数,以检查是否被拖动的项目 A) 有 preventCollapse 类和 B) 不是也被拖动的项目:
function addQuestionEventListeners(item) {
/* Checking to see if the item being dragged is an option for a question so that
the question won't collapse if it is */
item.ondragstart = function(e) {
if (!e.target.classList.contains('questionOption')) {
fullForm.style.height = (fullForm.offsetHeight) + 'px';
this.classList.add('dragging');
this.querySelector('.collapse').classList.remove('show');
};
}
item.ondragend = function(e) {
this.classList.remove('dragging');
this.querySelector('.collapse').classList.add('show');
fullForm.style.height='';
}
item.ondragenter = function(e) {
var dragging = document.querySelector('.dragging')
if(dragging.classList.contains('preventCollapse') && dragging !== this) {
this.querySelector('.collapse').classList.add('show');
}
}
}
谁能像我五岁一样解释为什么一个元素会调用自己的ondragenter 函数?这对我来说没有意义。