About the drag effect of H5

Keywords: Firefox network JSON Javascript

Dragging process:

  • dragstart: this event is triggered on the dragged element at the beginning of dragging. The listener needs to set the data required for dragging. This event is not triggered when dragging files from the operating system to the browser.
  • Regenter: trigger on the element when dragging the mouse to enter it. It is used to set visual feedback for the dragged element, such as highlighting
  • dragover: triggered when the mouse moves over the target element when dragging. The listener sets the element as a draggable element by preventing the browser's default behavior.
    -dragleave: triggered on the target element when the mouse moves out of the target element when dragging. At this time, the listener can cancel the visual effect set previously.
  • drag: triggered continuously on the dragged element during dragging
  • Drop: when the mouse is released on the drag and drop target, it is triggered on the drag and drop target. At this time, the listener needs to collect data and perform the required actions. If you drag and drop files from the operating system to the browser, you need to cancel the browser default behavior.
  • Drag: when the mouse is released on the drag target, it is triggered on the drag element. This event will not be triggered when the element is dragged from the browser to the operating system.

Reference link: https://www.jianshu.com/p/a821c72f91e6

Drag and drop events

 

By dragging events, we can control dragging a lot of things. What elements or where drag events happen is the most critical. Some events are triggered on the dragged element and some on the drop target. When dragging an element, the triggered events are: dragstart event, drag event and drag event.

When you press the mouse button and start moving the mouse, the dragstart event is triggered on the dragged element. At this time, the cursor changes to the "can't put" symbol (there is a backslash in the circle), indicating that you can't put the element on your own door. When the drag starts, you can run JavaScript code through the ondragstart event handler.

When the dragstart event is triggered, the drag event is triggered immediately, while the drag event is continuously triggered during the element being dragged. This event is similar to mousemove and touchmove events. When the drag stops (whether the element is placed on a valid or invalid placement target), the drag event occurs.

The target of the three events mentioned above is triggered by the dragged element. By default, the browser no longer changes the appearance of dragged elements during drag. But it can be modified by itself. However, most browsers create a translucent copy of the element being dragged, which always follows the cursor. When an element is dragged to an effective placement target, the events triggered are: dragener event, dragover event and dragleave or drop event.

As long as an element is dragged to the drop target, the dragender event (similar to the mouseover event) is triggered. The dragover event is followed by the dragover event, and is triggered continuously when the dragged element moves within the range of the target. If an element is dragged out of the drop target, the dragover event no longer occurs, but the dragleave event (similar to the mouseout event) is triggered. If the element is placed in the drop target, the drop event is triggered instead of the dragleave event. The target of the dragener event, the dragover event, and the dragleave or drop event are all elements that serve as placement targets.


Reference link: https://www.php.cn/html5-tutorial-376399.html

Problems encountered:

When taking over the project, you only need to consider the compatibility of the drag effect on Firefox. So after referring to various articles on the network, I think the problem may be that there is no data transfer set. The modified code is as follows, which can be dragged perfectly on Firefox.

 $('body').on('dragstart','.allSortContentList tr',function(e){
        dragElement = this;                                     // Used to store drag elements
        this.style.backgroundColor = '#FFF3E0 '; / / set the background of the drag element
        e.originalEvent.dataTransfer.setData("Text",e.target.id);  //Compatible with Firefox, dataTransfer must be set
    })
    $('body').on('dragend','.allSortContentList tr',function(e){
        e.target.style.backgroundColor = '#fff '; / / end of drag and drop to restore the background of drag element
        e.preventDefault();
    })

    $('body').on('drop','.allSortContentList tr',function(e){ //Change dragent to drop
        if(dragElement != this){
            this.parentNode.insertBefore(dragElement,this);     // Add the drag element to the front of the current element
        }
        e.stopPropagation(); //Prevent new page from opening on drag
        e.preventDefault();
    })

    $('body').on('dragleave','.allSortContentList tr',function(e){
        if(dragElement != this){
            if(lock && (this == this.parentNode.lastElementChild || this == this.parentNode.lastChild)){    // Last element when current element
                this.parentNode.appendChild(dragElement);       // Add drag element to the back
                lock = false;
            }else{
                lock = true;
            }
        }
        e.preventDefault();
    })

The complete implementation of the drag effect code of a table row is as follows:

//sort
    $('.sortCardBtn').click(function(){
        var dataList;
        if (type == 2){
            dataList = {
                "sellerId":sellerId,
                "type":2
            }
        }else if (type == 1){
            dataList = {
                "type":1
            }
        }

        /*Request to get a list of all cards*/
        $.ajax({
            url:path+"/shop/getSortGoodsInfoList.do",
            type:"post",
            data:dataList,
            success:function(data){
                if(data.status==0){
                    var list = data.data;
                    var currentSortBox = '';
                    currentSortBox += '<span class="layui-btn layui-btn-normal toSaveSortBtn">Save and modify</span><table class="layui-table">' +
                        '<thead><tr class="tableThread">' +
                        '<th>Commodity pictures</th>' +
                        '<th>Trade name</th>' +
                        '<th>Commodity type</th>' +
                        '<th>Commodity specification</th>' +
                        '<th>commodity price</th>' +
                        '<th>Maximum deduction amount of points</th>' +
                        '<th>Stock</th>' +
                        '<th>Sales volume</th>' +
                        '<th>threshold</th>' +
                        '<th>state</th>' +
                        '</tr></thead>' +
                        '<tbody class="allSortContentList">'
                    for(var i = 0;i<list.length;i++){
                        currentSortBox +='<tr draggable="true" id="'+list[i].id+'">';
                        currentSortBox += '<td><i><img class="imgSize" src="'+list[i].thumbnailUrl+'"></i></td>'+
                        '<td>'+list[i].name+'</td>'+
                        '<td>'+list[i].categoryName+'</td>'+
                        '<td>'+list[i].specification+'</td>';
                        if (list[i].sellPrice > 0){
                            currentSortBox+= '<td>'+list[i].sellPrice+'element</td>';
                        } else {
                            currentSortBox+= '<td>Free Admission</td>';
                        }
                        if (list[i].maxDeductAmount > 0){
                            currentSortBox+= '<td>'+list[i].maxDeductAmount+'element</td>';
                        }else {
                            currentSortBox+= '<td>-</td>';
                        }
                        currentSortBox+='<td>'+list[i].inventory+'</td>'+
                            '<td>'+list[i].saleCount+'</td>'+
                            '<td>'+list[i].threshold+'</td>'+
                            '<td class="option">'+(list[i].state == 1?'On shelves':'Off shelf')+'</td>';

                        currentSortBox+=	'</tr>';
                    }
                    currentSortBox += '</tbody></table>'
                    layer.open({
                        type: 1,
                        area: ['100%','100%'],
                        title:'Goods list sorting',
                        content: currentSortBox
                    });
                }else {
                    layer.msg(data.msg);
                }
            },
            error:function (data) {
                layer.msg('Abnormal network connection');
            }
        })
    })
    var dragElement = null;
    var lock = true;

    $('body').on('dragstart','.allSortContentList tr',function(e){
        dragElement = this;                                     // Used to store drag elements
        this.style.backgroundColor = '#FFF3E0 '; / / set the background of the drag element
        e.originalEvent.dataTransfer.setData("Text",e.target.id);  //Compatible with Firefox, dataTransfer must be set
    })
    $('body').on('dragend','.allSortContentList tr',function(e){
        e.target.style.backgroundColor = '#fff '; / / end of drag and drop to restore the background of drag element
        e.preventDefault();
    })

    $('body').on('drop','.allSortContentList tr',function(e){ //Change dragent to drop
        if(dragElement != this){
            this.parentNode.insertBefore(dragElement,this);     // Add the drag element to the front of the current element
        }
        e.stopPropagation(); //Prevent new page from opening on drag
        e.preventDefault();
    })

    $('body').on('dragleave','.allSortContentList tr',function(e){
        if(dragElement != this){
            if(lock && (this == this.parentNode.lastElementChild || this == this.parentNode.lastChild)){    // Last element when current element
                this.parentNode.appendChild(dragElement);       // Add drag element to the back
                lock = false;
            }else{
                lock = true;
            }
        }
        e.preventDefault();
    })
    document.ondragover = function(e){e.preventDefault();}          // dragover must be set to block default events
    document.ondrop = function(e){e.preventDefault();}
    $('body').on('click','.toSaveSortBtn',function(){
        $('.toSaveSortBtn').addClass('noClick')
        var finnalCardListId = [];
        $(this).siblings().find('.allSortContentList tr').each(function (index,item) {
            finnalCardListId.push(
                {
                    "id":item.id,
                    "number": index+1
                });
        });

        $.ajax({
            type:"post",
            url:path+"/shop/saveSort.do",
            dataType:"json",
            data:{
                "sortDataJson":JSON.stringify(finnalCardListId)
            },
            success:function(data){
                if(data.status==0){
                    layer.msg("Save successfully");
                    setTimeout(function(){
                        layer.closeAll()
                        var pageNum=$("#pageNum").val();
                        var pageSize=$("#pageSize").val();
                        loadList(pageNum,pageSize);
                        },3000)
                }else{
                    $('.toSaveSortBtn').removeClass('noClick')
                    layer.msg(data.msg);
                }
            },
            error:function(data){
                $('.toSaveSortBtn').removeClass('noClick')
                layer.msg('Abnormal network connection');
            }
        })
    })

 

Posted by PugJr on Thu, 24 Oct 2019 03:57:35 -0700