Detailed explanation of HTML5 native drag & drop Drag & Drop

Preface

Drag & drop are often encountered in our daily work. It means: grab the object and then drag it to another location. Currently, it is part of the HTML5 standard. I learned and practiced this function from several aspects.

Events corresponding to the drag-and-drop process

Let’s first look at the drag and drop process:

选中 --->  拖动  ---> 释放 

Then, let's take a step-by-step look at what happens during this process.

selected

In the HTML5 standard, to make an element draggable, set the draggable attribute to true.
Text, images, and links are draggable by default, and their draggable properties are automatically set to true.
Images and links can be dragged and dropped by holding down the left mouse button to select them.
Text can only be dragged and dropped if it is selected. If the draggable attribute of the display setting text is true, you can also drag and drop directly by holding down the left mouse button.

draggable attribute: Sets whether the element is draggable.
grammar:<element draggable="true | false | auto" >

  • true: can be dragged
  • false: disable dragging
  • auto: follows the browser definition of whether dragging is possible

drag

Every draggable element will go through three processes during the dragging process, 拖动开始--> 拖动过程中-->  拖动结束.

Targeted event name illustrate
dragged element drag start Fires when the element starts to be dragged
drag Fires repeatedly when an element is dragged
carrying Fires when the drag operation is completed
destination object more bearable Triggered when the dragged element enters the screen space occupied by the destination element
Dragover Triggered when the dragged element is within the destination element
dragleave Triggered when the dragged element leaves the destination element without being dropped.

The default behavior of the dragenter and dragover events is to refuse to accept any dragged element. Therefore, we must prevent this default behavior of the browser. e.preventDefault();

freed

After reaching the destination, release the element event

Targeted event name illustrate
destination object drop Triggered when the dragged element is dropped in the destination element. Generally, the browser's default behavior needs to be cancelled.

Select drag release example

<!DOCTYPE HTML>
<html>

<head>
    <title>拖放示例-文本</title>
</head>
<style>
.src {
    display: flex;
}

.dropabled {
    flex: 1;
}

.txt {
    color: green;
}

.img {
    width: 100px;
    height: 100px;
    border: 1px solid gray;
}

.target {
    width: 200px;
    height: 200px;
    line-height: 200px;
    text-align: center;
    border: 1px solid gray;
    color: red;
}
</style>

<body>
    <div class="src">
        <div class="dragabled">
            <div class="txt" id="txt">
                所有的文字都可拖拽。
                <p draggable="true">此段文字设置了属性draggable="true"</p>  
            </div>
            <div class="url" id="url">
                <a href="http://weiqinl.com" target="_blank">我是url:http://weiqinl.com</a>
            </div>
            <img class="img" id="tupian1" src="img1.png" alt="图片1" />
            <img class="img" id="tupian2" src="img2.png" alt="图片2" />
        </div>
        <div id='target' class="dropabled target">Drop Here</div>
    </div>
    <script>
        var dragSrc = document.getElementById('txt')
        var target = document.getElementById('target')

        dragSrc.ondragstart = handle_start
        dragSrc.ondrag = handle_drag
        dragSrc.ondragend = handle_end

        function handle_start(e) {
          console.log('dragstart-在元素开始被拖动时候触发')
        }

      function handle_drag() {
            console.log('drag-在元素被拖动时候反复触发')
        }

      function handle_end() {
            console.log('dragend-在拖动操作完成时触发')
        }

        target.ondragenter = handle_enter
        target.ondragover = handle_over
        target.ondragleave = handle_leave

        target.ondrop = handle_drop

        function handle_enter(e) {
            console.log('handle_enter-当元素进入目的地时触发')
            // 阻止浏览器默认行为
            e.preventDefault()
        }

        function handle_over(e) {
            console.log('handle_over-当元素在目的地时触发')
            // 阻止浏览器默认行为
            e.preventDefault()
        }

        function handle_leave(e) {
            console.log('handle_leave-当元素离开目的地时触发')
            // 阻止浏览器默认行为
            // e.preventDefault()
        }

        function handle_drop(e) {
            console.log('handle_drop-当元素在目的地放下时触发')
            var t = Date.now()
            target.innerHTML = ''
            target.append(t + '-拖放触发的事件。')
            e.preventDefault()
        }
    </script>
</body>

</html>

drag-drop event triggers

During the entire drag-and-drop process, what we talked about above is the superficial phenomenon. What else happens inside the event process? Please look at the DataTransfer object below.

DataTransfer object

The object dispatched at the same time as the event triggered by the drag-and-drop operation is DragEvent, which is derived from MouseEvent and has all the functions of Event and MouseEvent objects, and adds the dataTransfer attribute. This property is used to save drag-and-drop data and interaction information and return a DataTransfer object.
// DataTransfer dataTransfer = DragEvent.dataTransfer
There are many properties and methods defined by the DataTransfer object. Let's take a look at some of the standard ones.

Attributes illustrate
types Read-only property. It returns an array with the drag data format we set in the dragstart event. The formatting order is the same as the data order contained in the drag operation. IE10+, Edge, safari3.1, Firefox3.5+ and Chrome4 and above support this attribute
files Returns the list of files in the drag operation. Contains a list of all local files available for data transfer. If the drag operation does not involve dragging a file, this property is an empty list.
dropEffect Gets the type of the currently selected drag-and-drop operation or sets the operation to a new type. It should always be set to one of the possible values ​​of effectAllowed [none, move, copy, link]. Set dropEffect on the drop target in the dragover event handler.
effectAllowed Specifies the effects allowed for drag-and-drop operations. Must be one of them [none, copy, copyLink, copyMove, link, linkMove, move, all, uninitialized] The default is uninitialized, which means all effects are allowed. Set the effectAllowed attribute in the ondragstart handler
method illustrate
void setData(format, data) Sets the drag data for the drag operation to the specified data and type. format can be a MIME type
String getData(format) Returns data in the specified format. The format is consistent with setData().
void clearData([format]) Deletes data for a given type of drag operation. If data of the given type does not exist, this method does nothing. If no argument is given, all types of data are deleted.
void setDragImage(img, xOffset, yOffset) Specifies an image to display under the cursor when dragging occurs. In most cases there is no need to set this, as the dragged node is created as a default image. The x and y parameters respectively indicate the horizontal and vertical offset of the image.
//IE10及之前版本,不支持扩展的MIME类型名
//Firefox 5版本之前,不能正确的将url和text映射为text/uri-list 和text/plain
var dataTransfer = event.dataTransfer;
//读取文本,
var text = dataTransfer.getData("Text");
//读取URL,
var url = dataTransfer.getData("url") || dataTransfer.getData("text/uri-list");

Examples of various attribute methods of drag-drop-dataTransfer

Browser support

Having said all this, if the browser does not support it, it is all nonsense.

Method of easily dragging and dropping elements on a page, requiring minimal JavaScript.
Requires minimal js, a simple method to drag page elements

Drag

Browser support for drag--caniuse

note

  • dataTransfer.items Only supported by Chrome
  • dropzoneProperty, currently not supported by browsers
  • Firefox supports .setDragImageany type of DOM element. Chrome must have HTMLImageElementor any DOM element attached to the DOM and the browser's .setDragImageviewport.
    1. Partial support means no support dataTransfer.files or  .typesobject
    2. Partial support means no support .setDragImage
    3. Partial support means dataTransfer.setData / getData limited support format

Below, what I encountered in practice is that each browser has different implementations of standards.

  • getData()In the Chrome 62.0 browser, it can only droptake effect in events.
  • If using setDragImagemethod, the specified image does not exist, then the drag process:
    1. Safari 11.0.1 browser will only trigger dragstartand dragendevents.
    2. Chrome, Opera and Firefox will trigger other events normally.
  • For each drag-and-drop operation, Firefox will perform the action of opening a new page and automatically search for the dataTransfer.getData()obtained content.
    As a workaround, in dropthe event, add:  e.stopPropagation();// 不再派发事件。解决Firefox浏览器,打开新窗口的问题.
  • In Opera 49 version, links cannot be dragged by default, and draggablethe properties must be set to truebefore they can be dragged.
  • About  dropEffect and  effectAllowed .
    1. effectAllowed There will be no more than a few effects that allow drag-and-drop operations. dropEffect Setting the specific effect of the drag-and-drop operation can only be one of four possibilities.
    2. If effectAllowedset to none, dragging and dropping of elements is not allowed. However, the events that can be triggered by each browser are different. (Note: Safari can drag and drop elements, and all events will be triggered)
    3. If dropEffectset to none, dragging and dropping into the destination element is not allowed.
    4. If the value of is set effectAllowed, then if dropEffectthe value is to be set, its value must be effectAllowedconsistent with the value of , otherwise the dragging effect will be invalid, and the dragged element will not be allowed to be placed into the destination element. (Note: Safari 11.0.1 works, and it can also be dragged into the destination element, but this does not meet the standards).

Example

Examples of drag-drop-dataTransfer attribute methods
drag-drop event triggering

Summarize

Native HTML5 drag and drop API, drag & drop will still be encountered in many situations in actual work.
Above, I only introduced some commonly used APIs. The API is not complicated, just read it for a while and you will know it through practice. Each browser may have slightly different performance, but I believe everyone will still develop towards standards.

 

Guess you like

Origin blog.csdn.net/delishcomcn/article/details/132400972