preface
Drag and drop (DRAP && drop) in our usual work, often encountered. It means: grab an object and drag it to another location. Currently, it is part of the HTML5 standard. I learned and practiced this feature in several ways.
Drag-and-drop processes correspond to events
Let’s take a look at the drag-and-drop process:
Select --> Drag --> ReleaseCopy the code
And then, let’s take a look at what happens in the process.
The selected
In the HTML5 standard, to make elements dragable, the draggable property is set to true. Text, images, and links are drag-and-drop by default, and their draggable property is automatically set to True. Images and links can be dragged and dropped by holding down the left mouse button. Text can only be dragged and dropped if it is selected. If the display Settings text draggable property is true, hold down the left mouse button to drag and drop directly.
Draggable property: Sets whether an element can be dragged. Grammar: < element draggable = “true | | false auto” >
- True: Can be dragged
- False: Forbid dragging
- Auto: Follows the browser definition to determine whether dragging can be performed
Drag the
Every draggable element, as it drags, goes through three processes: drag begins > drag begins > drag ends.
In view of the object | The name of the event | instructions |
---|---|---|
The element being dragged | dragstart | Triggered when the element starts to be dragged |
drag | Fires repeatedly as the element is dragged | |
dragend | Triggered when the drag operation is complete | |
Destination object | dragenter | Triggered when an element is dragged into the screen space occupied by the destination element |
dragover | Fired when the dragged element is inside the destination element | |
dragleave | Triggered when the dragged element leaves the destination element without dropping it |
The default behavior of the Dragenter and dragover events is to reject any drag-and-drop elements. Therefore, we must prevent the browser from default behavior. e.preventDefault();
The release of
When the destination is reached, the element event is released
In view of the object | The name of the event | instructions |
---|---|---|
Destination object | drop | Triggered when the dragged element is dropped in the destination element, generally undoing the browser’s default behavior. |
Select drag to release the example
<! DOCTYPE HTML> < HTML> <head> <title> drag and drop examples - text </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"Word-wrap: break-word! Important; "> < p style =" max-width: 100%; <p draggable="true"> This text sets the property draggable="true"</p>
</div>
<div class="url" id="url">
<a href="http://weiqinl.com" target="_blank"> I am url:http://weiqinl.com</a> </div> <img class="img" id="tupian1" src="img1.png" alt="Picture 1" />
<img class="img" id="tupian2" src="img2.png" alt="Photo 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 - triggered when the element starts to be dragged')}function handle_drag() {
console.log('Drag - Triggered repeatedly when an element is dragged')}function handle_end() {
console.log('Dragend - triggered when the drag operation is complete')
}
target.ondragenter = handle_enter
target.ondragover = handle_over
target.ondragleave = handle_leave
target.ondrop = handle_drop
function handle_enter(e) {
console.log('HANDle_enter - triggered when the element enters the destination') // block browser default behavior e.preventDefault()}function handle_over(e) {
console.log('HANDle_over - fires when element is at destination') // block browser default behavior e.preventDefault()}function handle_leave(e) {
console.log('HANDle_leave - triggered when an element leaves its destination'// block browser default behavior // e.preventDefault()}function handle_drop(e) {
console.log('HANDle_DROP - Triggered when the element is dropped at the destination')
var t = Date.now()
target.innerHTML = ' '
target.append(t + '- drag-and-drop triggered events. ')
e.preventDefault()
}
</script>
</body>
</html>Copy the code
Drag-drop Event is triggered
What else is going on inside the drag-and-drop process? Take a look at the DataTransfer object at 👇 below.
The DataTransfer object
The object dispatched along with the Event triggered by the drag-and-drop operation is the DragEvent, which is derived from MouseEvent and has all the functionality of an Event and a MouseEvent object, with the addition of the dataTransfer attribute. This property is used to hold drag-and-drop data and interaction information and return a DataTransfer object. // DataTransfer DataTransfer = dragEvent. DataTransfer There are many types of properties and methods defined by DataTransfer objects.
attribute | instructions |
---|---|
types | Read-only property. It returns an array of drag data formats that we set in the Dragstart event. The format order is the same as the order of the data contained in the drag operation. This property is supported by Internet explorer 10+, Edge, safari3.1, Firefox3.5+, and Chrome4 |
files | Returns the list of files in the drag operation. Contains a list of all local files available for data transfer. If a drag operation does not involve a drag 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 for Effectalhoward (None, move, copy, link). Dragover event handler sets the dropEffect for the drop target. |
effectAllowed | Specifies the effects allowed for drag-and-drop operations. The value must be none (copy, copyLink, copyMove, link, linkMove, move, all, uninitialized). The default value is uninitialized to allow all effects. Set the effectalhoward property in the onDragStart handler |
methods | instructions |
---|---|
void setData(format, data) | Sets the drag data for a drag operation to the specified data and type. Format can be a MIME type |
String getData(format) | Returns data in the specified format, as in setData() |
void clearData([format]) | Deletes data for the given type of drag operation. If data of a given type does not exist, this method does nothing. If no parameter is given, all types of data are deleted. |
void setDragImage(img, xOffset, yOffset) | Specifies an image to display below the cursor when a drag occurs. In most cases, this is not required because the dragged node is created as the default image. X and y parameters indicate the horizontal and vertical offsets of the image respectively |
// Internet Explorer 10 and earlier do not support extended MIME type names //Firefox 5 and earlier, Var dataTransfer = event. DataTransfer; var dataTransfer = event. Var text = datatransfer.getData ("Text"); Var URL = datatransfer.getData ("url") || dataTransfer.getData("text/uri-list");Copy the code
Examples of drag-drop-datatransfer property methods
Browser support
Having said that, if the browser does not support it, it is nonsense.
Method of easily dragging and dropping elements on a page, requiring minimal JavaScript. Requires minimal JS to implement a simple way to drag and drop page elements
Browser support for Drag — Gain note on Caniuse
dataTransfer.items
Chrome onlydropzone
Property, currently not supported by browsers- Firefox supports
.setDragImage
Any type of DOM element. Chrome must haveHTMLImageElement
Or any DOM element that is attached to the DOM and the browser’s.setDragImage
Inside the viewport.
1. Partially supported means not supporteddataTransfer.files
or.types
object
2. Partially supported means not supported.setDragImage
3. Partial support meansdataTransfer.setData / getData
Limited support for formats
Here’s what I’ve seen in practice: Browsers implement the standard differently.
getData()
In Chrome 62.0, only thedrop
Event in effect.- If you are using
setDragImage
Method, the specified image does not exist, then the drag process:- Safari 11.0.1 will only trigger
dragstart
anddragend
Events. - Chrome, Opera, and Firefox will normally trigger other events.
- Safari 11.0.1 will only trigger
- For every drag-and-drop operation, Firefox performs a new page opening action and searches automatically
dataTransfer.getData()
Get the content.
The solution, indrop
Event, add:e.stopPropagation(); // No more events are sent. Resolve the Firefox browser to open a new window
. - In Opera 49, links cannot be dragged by default
draggable
Property set totrue
Before you can drag. - about
dropEffect
和effectAllowed
。effectAllowed
There are no more than a few drag-and-drop effects allowed.dropEffect
Setting the exact effect of a drag and drop operation can only be one of four possibilities.- if
effectAllowed
Set tonone
Is not allowed to drag and drop elements. However, each browser can trigger different events. (Note: Safari can drag and drop elements, and all events are triggered) - if
dropEffect
Set tonone
Is not allowed to be dragged and dropped into the destination element. - If you set it up
effectAllowed
So if you want to setdropEffect
, whose values must be andeffectAllowed
Otherwise, the drag effect is invalid, and the dragged element is not allowed to be placed in the destination element. (note: safari11.0.1 works and can also be dragged into destination elements, but this is not standard).
The sample
Drag-drop-datatransfer Each attribute method Example drag-drop Event firing
conclusion
Native HTML5 drag and drop API, Drag && drop in practice, there are still a lot of situations. Above, I’ve covered only a few of the commonly used apis. API is not complicated, watch a little bit, practice will know. Browsers may behave a little bit differently, but I think people will move towards standards. By the way, for the first time writing an article in Nuggets, markdown editor is awesome at 👍. Blog park address: www.cnblogs.com/weiqinl