Home > Web Front-end > H5 Tutorial > Example explanation of HTML5 DragEvent interface

Example explanation of HTML5 DragEvent interface

零下一度
Release: 2017-05-26 15:41:48
Original
2116 people have browsed it

DragEvent is a DOM event interface that represents the interaction between drag and drop. The user starts dragging by placing a pointing device (such as a mouse) on the target's surface, and then drags the pointer to a new location (such as another DOM element). The application automatically resolves drag-and-drop interactions. The DragEvent interface inherits properties from mouseEvent and Event.

Event types

DragEvent is not a single event, it contains multiple events, these events are: drag, dragstart, dragenter, dragend, dragover, dragexit, dragleave , drop.

drag: This event is triggered repeatedly during the dragging process of the element, once every 100 milliseconds. The target element of this event is the dragged element. This event can bubble up and cancel the default behavior.

dragstart: This event is triggered when the user starts dragging. The target element of this event is the element being dragged. Among these events, the dragstart event is triggered first. This event can bubble up and cancel the default behavior.

dragenter: This event is triggered when the dragged element enters a legal droppable target. The target element of this event is the droppable target. This event can bubble up and cancel the default behavior.

dragover: This event is triggered repeatedly when the dragged element moves within the drop target range, once every 100 milliseconds. The target element of this event is the droppable target. This event can bubble up and cancel the default behavior.

dragend: This event is triggered when dragging ends. The target element of this event is the dragged element. Dragend fires last among these events. This event can bubble up and cannot cancel the default behavior.

dragleave: This event is triggered when the dragged element leaves a legal droppable target. The target element of this event is the droppable target. This event can bubble up and cannot cancel the default behavior.

dragexit: This event is triggered when a droppable element is no longer the nearest drop target of the drag operation. The target element of this event is the droppable element. This event can bubble up and will not cancel the default behavior.

drop: This event is triggered when the pointer device of the dragged element is released on the dropable target. The target element of this event is the droppable target. The drop event fires before the dragend event fires. This event can bubble up and cancel the default behavior.

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>test target</title>
    <style type="text/css">
        #drag{
            width:200px;
            height:200px;
            background-color: aqua;
        }
        .drop{
            width: 300px;
            height: 300px;
            background-color: antiquewhite;
        }
    </style>
</head>
<body>
    <p id="drag" draggable="true" ondragstart="event.dataTransfer.setData(&#39;text/plain&#39;,&#39;dddd&#39;)">
        我可以拖动
    </p>
    <img src="test.jpg" id="img">
    <p class="drop"></p>
    <script type="text/javascript">
        document.addEventListener(&#39;drag&#39;,function(event){
            event.target.style.backgroundColor = &#39;black&#39;;
        },false);
        document.addEventListener(&#39;dragstart&#39;,function(event){
            event.target.style.backgroundColor = &#39;red&#39;;

        },false);
        document.addEventListener(&#39;dragend&#39;,function(event){
            event.target.style.backgroundColor = &#39;yellow&#39;;
        },false);
        document.addEventListener(&#39;dragover&#39;,function(event){
            event.preventDefault();
            event.target.style.backgroundColor = &#39;blue&#39;;
        },false);
        document.addEventListener(&#39;dragenter&#39;,function(event){
            event.target.style.backgroundColor = &#39;green&#39;;
        },false);
        document.addEventListener(&#39;dragleave&#39;,function(event){
            event.target.style.backgroundColor = &#39;pink&#39;;
        },false);
        document.addEventListener(&#39;dragexit&#39;,function(event){
            event.target.style.backgroundColor = &#39;red&#39;
        },false);
        document.addEventListener(&#39;drop&#39;,function(event){
            event.preventDefault();
            event.target.style.backgroundColor = &#39;white&#39;;
            console.log(2);


        },false)
    </script>
</body>
</html>
Copy after login

The event objects of these events contain the methods and properties of the event objects of mouse events. In addition, there is also a dataTransfer attribute

making the element draggable

In HTML, the only draggable elements by default are image, link and selected text. To make other elements draggable, you need to do the following three things:

1. Set a draggable attribute to the element, and set the value of this attribute to true

2. In this element Add a dragstart event listener

3. Set the drag data on the dragstart event listener through event.DataTransfer.setData(type, value).

<p draggable="true" ondragstart="event.dataTransfer.setData(&#39;text/plain&#39;, &#39;This text may be dragged&#39;)">
      This text <strong>may</strong> be dragged.
    </p>
Copy after login

If the draggable attribute is disabled or set to false, then this element cannot be dragged. The draggable attribute can be set on any property. When an element is set to draggable, clicking or dragging the mouse on the element will not select the text or other elements in the element. When the user starts dragging, the dragstart event will be triggered. In the dragstart event, you can specify the drag data through setData(), specify the image feedback through setDragImage(), and specify the drag effect by setting the effectAllowed attribute and dropEffect attribute. Drag data must be specified, but the picture feedback is that the drag effect is not necessary

Drag data

Drag data contains two parts of information, namely the type of data and the value of the data , the data type is String, and the data value is also in the form of a string. The types of drag and drop data include: text/plain, text/html, image/jpeg, text/uri-list, etc. You can also customize the type.

You can call the setData() method multiple times to set multiple drag and drop data. As follows:

var dt = event.dataTransfer;
dt.setData("application/x-bookmark",bookmarkString);
dt.setData(&#39;text/uri-list&#39;,&#39;www.baidu.com&#39;);
dt.setData(&#39;text/plain&#39;,&#39;drag data&#39;);
Copy after login

application/x-bookmark is a custom type.

If you set a new type of data through this method, then the new drag data will be at the end of the drag data list. If you set the existing type of data, then the new data will overwrite the old one. data.

The specified type of drag and drop data can be obtained through getData()

The specified type of drag and drop data can be cleared through clearData()

Picture feedback

Image feedback does not have to be set. By default, it is a translucent image generated from the drag target, and this image will follow the mouse movement during dragging. You can customize image feedback through the setDragImage(image,xOffect,yOffect) method.

setDragImage() accepts three parameters. The first parameter represents the picture reference , and the second and third parameters represent the position of the upper left corner of the picture relative to the mouse pointer. The unit is pixels

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>test target</title>
    <style type="text/css">
        #drag{
            width:200px;
            height:200px;
            background-color: aqua;
        }
        .drop{
            width: 300px;
            height: 300px;
            background-color: antiquewhite;
        }
    </style>
</head>
<body>
    <p id="drag" draggable="true" ondragstart="event.dataTransfer.setData(&#39;text/plain&#39;,&#39;dddd&#39;)">
        我可以拖动
    </p>
    <img src="test.jpg" id="img">
    <p class="drop"></p>
    <script type="text/javascript">
      
        document.addEventListener(&#39;dragstart&#39;,function(event){
            event.target.style.backgroundColor = &#39;red&#39;;
            event.dataTransfer.setDragImage(document.getElementById(&#39;img&#39;),30,30);

        },false);
       
    </script>
</body>
</html>
Copy after login

Drag effect

You can specify the drag effect by setting effectAllowed and dropEffect

事件对象的dataTransfer属性

dataTransfer属性是一个DataTransfer对象,在这个属性中保存了拖拽操作过程中的数据,它可能保存一个或者多个数据项。这个属性是只读的。

dataTransfer属性中的标准属性

1.dropEffect

得到当前drag and drop操作的类型,或者设置给当前drag and drop 设置新的类型。这个属性可能取值是none,copy,move,link。这属性会影响拖拽过程中的鼠标的显示形式。

2.effectAllowed

这个属性用于指定运行的拖拽操作效果,可选的值有none,all,copy,move,link,copyLink,copyMove,linkMove。默认情况这个值是all,如果要设置这个属性的值就要在dragstart的事件处理程序里进行设置。

3.files

包含了在data transfer中的所有可用的本地文件列表,如果被拖拽操作没有涉及文件,那么它是一个空列表。

4.items

是一个包含了所有拖拽数据的列表。它是一个DataTransferItemList对象。

5.types

它是一个字符串数组,这个数组中包含在dragstart事件处理程序中设置的拖拽事件的类型,如果拖拽操作不存在数据,那么他得到一个空数组。

DataTransfer属性的标准方法

1.clearData(type):移除给定类型相关的拖拽数据。接受一个可选的参数,如果这个参数是空或者没有指定,那么移除所以类型的数据,如果指定的类型不存在或者data transfer中不包含数据,那么这个方法不会产生什么影响。

2.getData(type):得到指定类型的拖拽数据。如果指定类型的数据不存在或者data transfer中不包含数据, 得到一个空的字符串。

3.setData(type,value):设置给定类型的拖拽数据。接受两个参数,第一个参数是类型,第二个参数是指定类型的值。 如果这个类型的值不存在,那么在类型列表的最后添加一个新的格式,如果已经存在的,那么在相同的位置 存在的数据被替换.

4.setDragImage(image,xoffset,yoffset):接受三个参数,第一个参数是图片的引用,第二个和第三个参数是移动的图片的 左上角相对鼠标的位置。

DataTransferList对象

通过dataTransfer.items得到的值就是DataTransferList对象。

DataTransferList对象的属性

1.length:得到拖拽数据的数量

DataTransferList对象的方法

1.add():向拖拽数据列表中添加一个新的拖拽数据,添加成功后返回这个新的拖拽数据。当添加一个文件到拖拽数据列表中,这个方法只接受一个文件对象作为参数。当添加一个给定 类型的字符串到拖拽数据列表中,这个方法接受两个参数,第一个参数是数据,第二个参数是类型。

2.remove(index):从拖拽数据列表中移除指定位置的拖拽数据。这个方法接受一个表示位置的参数,如果这个参数小于0或者大于拖拽数据列表的长度,拖拽数据列表不会发生改变。

3.clear():移除拖拽数据列表中所有的拖拽数据。不需要参数。

4.DataTransferItem(index):得到指定位置上的拖拽数据。接受一个表示位置的参数, 这个方法简写形式是数组索引

DataTransferItem对象

dataTransfer.items中的每一项都是DataTransferItem对象。

DataTransferItem对象的属性

1.kind:得到拖拽数据的键,可能的值有file和string

2.type:得到拖拽数据的类型,是MINE type

DataTransferItem对象的方法

1.getAsFile():返回拖拽数据的文件对象。如果拖拽数据不是文件则返回null

2.getAsString(function):调用回调函数,这个回调函数将拖拽数据项的字符串形式作为它的参数

拖拽文件

要使文件能够被拖放的一个重要步骤是定义一个放置区域。并且为放置区域添加drop,dragover和dragend事件处理程序。

当为一个元素添加drop事件的处理程序,及在dragover事件处理程序中取消浏览器的默认行为,那么这个元素就是放置区域。

另外,在drag和drop操作结束之后,应用程序应该移除拖拽数据(可能是一个或者多个文件),数据的清理通常在 dragend事件处理程序中。

<p id="drop_zone" ondrop="drop_handler(event);" ondragover="dragover_handler(event);" ondragend = "dragend_handler(event)">
  <strong><Drag one or more files to this Drop Zone ...</strong>
</p>
Copy after login

例子一,访问文件名

function drop_handler(ev) {
  console.log("Drop");
  ev.preventDefault();
  // If dropped items aren&#39;t files, reject them
  var dt = ev.dataTransfer;
  if (dt.items) {
    // Use DataTransferItemList interface to access the file(s)
    for (var i=0; i < dt.items.length; i++) {
      if (dt.items[i].kind == "file") {
        var f = dt.items[i].getAsFile();
        console.log("... file[" + i + "].name = " + f.name);
      }
    }
  } else {
    // Use DataTransfer interface to access the file(s)
    for (var i=0; i < dt.files.length; i++) {
      console.log("... file[" + i + "].name = " + dt.files[i].name);
    }
  }
}
Copy after login

例子二,阻止浏览器默认行为

function dragover_handler(ev) {
  console.log("dragOver");
  // Prevent default select and drag behavior
  ev.preventDefault();
}
Copy after login

例子三,清除数据

function dragend_handler(ev) {
  console.log("dragEnd");
  // Remove all of the drag data
  var dt = ev.dataTransfer;
  if (dt.items) {
    // Use DataTransferItemList interface to remove the drag data
    for (var i = 0; i < dt.items.length; i++) {
      dt.items.remove(i);
    }
  } else {
    // Use DataTransfer interface to remove the drag data
    ev.dataTransfer.clearData();
  }
}
Copy after login

【相关推荐】

1. 免费h5在线视频教程

2. Understand html5 in 20 minutes and see what new features H5 has.

3. Teach you how to implement an H5 micro-scene

4. Code example for making a registration page in H5

5. The difference between H5 and traditional html

6. Passed Detailed explanation of examples of H5 implementing the camera function

The above is the detailed content of Example explanation of HTML5 DragEvent interface. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template