JavaScript Advanced Programming---Drag events

Source: Internet
Author: User

Drag events

Drag refers to the user pressing the mouse button on an object, dragging it to another location, and then releasing the mouse button to place the object there.

There are several types of dragged objects, including element nodes, pictures, links, selected text, and so on. In an HTML page, except that the element node is not dragged by default, other (images, links, selected text) can be dragged directly. In order for the element node to be dragged, you can set the Draggable property of the node to true.

<div draggable= "True" >  this area can be dragged </div>

The Draggable property can be used with any element node, but the picture (img element) and the link (a element) do not add this attribute, it is possible to drag. For them, when used with this property, it is often set to false to prevent drag.

Note that once an element node's Draggable property is set to True, it is no longer possible to select the text or child nodes inside the node with the mouse.

Event Type

When the element node or selected text is dragged, the drag event continues to be triggered, including some of the following events.

  • Drag event: A continuous trigger on the dragged node during the drag process.

  • DragStart Event: The drag start is triggered on the dragged node, and the target property of the event is the dragged node. You should usually specify the dragged data in the listener function of this event.

  • Dragend Event: When the drag ends (releasing the mouse button or pressing the Escape key) is triggered on the dragged node, the target property of the event is the dragged node. It is triggered on the same node as the DragStart event. The Dragend event is always triggered regardless of whether the drag is across the window or is canceled halfway.

  • DragEnter event: When dragged into the current node, triggered on the current node, the target property of the event is the current node. In this event, you should typically specify whether to allow data to be dragged down (drop) at the current node. If the current node does not have a listener function for the event, or if the listener function does nothing, it means that the data is not allowed to be dropped at the current node. Visually dragging into the current node is also set in the listener function of this event.

  • DragOver event: When dragged over the current node, fires continuously on the current node, and the target property of the event is the current node. This event is basically similar to the DragEnter event, which resets the effect of the current drag event (the DropEffect property of the DataTransfer object) to none, which means that the dragged node is not allowed to drop, so if drop data is allowed on the current node, Typically, the Preventdefault method is used to cancel the reset drag effect to none.

  • DragLeave event: Triggered on the current node when dragged away from the current node range, the target property of the event is the current node. Visually dragging and dropping away from the current node is set in the listener function of this event.

  • Drop event: The dragged node or selected text, when released to the target node, is triggered on the target node. Note that if the current node does not allow drop, the event is not triggered even if the mouse button is released above the node. If the user presses the Escape key, the action is canceled and the event is not triggered. The listener function of the event is responsible for removing the dragged data and processing it.

  • The drag-and-pull process only triggers these drag events, although the mouse is moving, but the mouse events do not trigger.

  • Dragging files from the operating system into the browser does not trigger the DragStart and Dragend events.

  • A listener function for the DragEnter and DragOver events that specifies the data that can be dragged down (drop). Because most areas of the Web page do not work together as the target node for the drop, the default setting for these two events is that the current node does not allow drop. If you want to drop dragged data on the target node, you must first block the default behavior of both events, or cancel both events.

<div ondragover= "return false" ><div ondragover= "Event.preventdefault ()" >

  

In the above code, it is not possible to drop a dragged node on a div node without canceling the drag event or blocking the default behavior.

The drag event is represented by a Dragevent object that inherits the MouseEvent object and therefore inherits the Uievent and event objects. The Dragevent object has only one unique property datatransfer, and the others are inherited properties. The DataTransfer property is used to read and write data transmitted in a drag event, as described in the DataTransfer object section below.

The following example shows how to dynamically change the background color of a dragged node.

Div.addeventlistener ("DragStart", function (e) {  this.style.backgroundColor = "Red";}, False); Div.addeventlistener ("Dragend", function (e) {  this.style.backgroundColor = "green";}, False);

  

In the above code, when the div node is dragged, the background color changes to red, the drag ends and the green is turned back.

Here is an example that shows how to drag a node from the current parent node to another parent node.

/HTML code for//<div class= "Dropzone" >//<div id= "draggable" draggable= "true" >//the node can be dragged//</div> </div>//<div class= "Dropzone" ></div>//<div class= "Dropzone" ></div>//<div class = "Dropzone" ></div>//dragged node var dragged;document.addeventlistener ("DragStart", function (event) {//Save dragged node Dr  agged = Event.target; The background color of the dragged node becomes transparent event.target.style.opacity =. 5;}, False);d Ocument.addeventlistener ("Dragend", function (event) {//dragged The background color of the pull node returns to normal event.target.style.opacity = "";}, False);d Ocument.addeventlistener ("DragOver", function (event) {//Prevent drag-and-drop effect) The result is reset, allowing the dragged node to be placed in the target node Event.preventdefault ();}, False);d Ocument.addeventlistener ("DragEnter", function (event) {// The background color of the target node becomes purple//Because the event bubbles, so filter the node if (event.target.className = = "Dropzone") {event.target.style.background = "purple  "; }}, False);d Ocument.addeventlistener ("DragLeave", function (event) {//the background color of the target node is restored as is if (Event.target.className = = "Dr Opzone "{event.target.style.background = ""; }}, False);d Ocument.addeventlistener ("Drop", function (event) {///prevents the default behavior of the event (for example, some elment nodes can open the link) event.preventdefault  ();    if (Event.target.className = = "Dropzone") {//Restore target node background color event.target.style.background = "";    The dragged node is inserted into the target node dragged.parentNode.removeChild (dragged);  Event.target.appendChild (dragged); }}, False);

  

DataTransfer Object Overview

All drag events have a DataTransfer property that is used to hold the data that needs to be passed. The value of this property is a DataTransfer object.

The dragged data holds two aspects of data: the type of data (aka format) and the value of the data. The type of data is a MIME string, such as Text/plain or image/jpeg, and the value of the data is a string. In general, if you drag a piece of text, the data is the default text; If you drag a link, the data defaults to the URL of the link.

The data type and data values can be provided when the drag event begins, and during the drag-and-drop event, the data type is checked through the listener function of the DragEnter and DragOver events to determine if the dropped dragged object is allowed to drop. For example, check that the dragged data type is text/uri-list in only the area where the link is allowed to drop.

When a drop event occurs, the listening function takes out the dragged data and processes it.

Methods for DataTransfer objects

The DataTransfer object has the following methods.

(1) SetData ()

The SetData method is used to set the data of the specified type with the event. It takes two parameters, the first one is the data type, and the second is the specific data. If the specified type does not exist in the existing data, the type is written to the types property, and if it already exists, the existing data in that type is replaced.

Event.dataTransfer.setData ("Text/plain", "Text to drag");

  

The above code adds data in plain text format to the event.

If you drag the text box or drag the selected text, the text data is added to the DataTransfer property by default, without specifying it manually.

<div draggable= "true" ondragstart= "  event.dataTransfer.setData (' Text/plain ', ' BBB ')" >  aaa</div >

  

In the above code, the drag data is actually BBB, not AAA.

The following is the addition of other types of data. Since Text/plain is the most commonly supported format, in order to ensure compatibility, it is recommended to always save the data in a plain text format.

var dt = event.datatransfer;//Add link dt.setdata ("Text/uri-list", "http://www.example.com");d t.setdata ("Text/plain", " Http://www.example.com ");//Add HTML code dt.setdata (" text/html "," Hello there, <strong>stranger</strong> "); Dt.setdata ("Text/plain", "Hello there, <strong>stranger</strong>");//Add Image Urldt.setdata ("text/ Uri-list ", ImageUrl);d t.setdata (" Text/plain ", ImageUrl);

You can provide data in multiple formats at once.

var dt = Event.datatransfer;dt.setdata ("Application/x-bookmark", bookmarkstring);d t.setdata ("text/uri-list", "http ://www.example.com ");d t.setdata (" Text/plain "," http://www.example.com ");

The above code, by storing three types of data on the same event, allows the drag event to drop different values on top of different objects. Note that the first format is a custom format that the browser cannot read by default, which means that only a node that has a specific code deployed will be able to drop (read) this data.

GetData ()

The GetData method takes a string (representing the data type) as a parameter, returning the data of the specified type with the event (usually the data added with the SetData method). If the data of the specified type does not exist, an empty string is returned. Usually only the drop event is triggered before the data can be fetched. If you take out the data stored in another domain name, you will get an error.

The following is a listener function for the drop event that is used to fetch data of the specified type.

function OnDrop (event) {  var data = Event.dataTransfer.getData ("Text/plain");  event.target.textContent = data;  Event.preventdefault ();}

  

The above code takes out the text data of the dragged event and replaces it with the text content of the current node. Note that the default behavior of the browser must also be canceled, because if the user drags a link, the browser opens the link in the current window by default.

The GetData method returns a string that must be parsed manually if it contains more than one item of data.

function Dodrop (event) {  var lines = event.dataTransfer.getData ("Text/uri-list"). Split ("\ n");  For (Let line of lines) {let    link = document.createelement ("a");    Link.href = line;    Link.textcontent = line;    Event.target.appendChild (link);  }  Event.preventdefault ();}

  

In the above code, the GetData method returns a set of links that must be parsed on its own.

The type value is specified as a URL, and the first valid link can be removed.

var link = event.dataTransfer.getData ("URL");

  

ClearData ()

The ClearData method takes a string (representing the data type) as a parameter, deleting the data of the specified type with the event. If no type is specified, all data is deleted. If the specified type does not exist, the original data is not affected.

Event.dataTransfer.clearData ("Text/uri-list");

The above code clears the URL data with the event.

Setdragimage ()

During the drag process (after the DragStart event is triggered), the browser displays a picture that moves with the mouse to represent the dragged node. This image is created automatically and is usually displayed as the appearance of the dragged node and does not need to be set up yourself. The Setdragimage method can be used to customize the picture, which accepts three parameters, the first is an IMG picture element or a canvas element, and if omitted or null, the appearance of the dragged node is used, and the second and third parameters are the horizontal and the right coordinates of the mouse relative to the upper-left corner of the picture.

Here is an example.

HTML code for//<div id= "Drag-with-image" class= "Dragdemo" draggable= "true" >     drag me//</div>var div = document.getElementById ("Drag-with-image");d Iv.addeventlistener ("DragStart", function (e) {  var img = Document.createelement ("img");  IMG.SRC = "Http://path/to/img";  E.datatransfer.setdragimage (IMG, 0, 0);}, False);

  

JavaScript Advanced Programming---Drag events

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.