Why is my ondragstart operation being undone immediately after executing?

情到浓时终转凉″ 提交于 2020-06-17 09:29:32

问题


I'm making a drag-and-drop form builder with three levels of grouping: Sections, which contain Questions, which contain Options. Options can be dragged within and between Questions, and Questions can be dragged within and between Sections, and Sections can be ordered amongst each other.

I'm using Bootstrap's collapse/show classes to hide the majority of Questions as they begin being dragged, since some can have a dozen plus options, and leaving it open while dragging wouldn't let you see any questions beneath it.

However, as soon as the ondragstart executes and removes the show class from the body of the Question, collapsing it, it seems to be undone immediately.

I tried stepping through each and every line that gets called after ondragstart in the debugger, and couldn't find anything that would re-add the show Bootstrap class.

Fiddle: https://jsfiddle.net/robertgreenstreet/jrdmvasw/4/


回答1:


It turns out all I needed was to add a condition to the ondragenter function for Questions to check whether the item being dragged A) Had the preventCollapse class AND B) Was NOT also the item being dragged over:

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');
        }
    }
}

Can anyone explain like I'm five why an element would call its own ondragenter function? It doesn't make sense to me.



来源:https://stackoverflow.com/questions/62072260/why-is-my-ondragstart-operation-being-undone-immediately-after-executing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!